Skip to content
Advertisement

Kotlin Stream peek(…) method

What is the best alternative in Kotlin to java.util.stream.Stream<>.peek(…)?

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#peek-java.util.function.Consumer-

Seems there are no alternative intermediate operations:

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.streams/index.html

I found only terminating forEach(…)

Advertisement

Answer

The Stream alternative in Kotlin is Sequences.

 listOf(1, 2, 3, 4, 5)
    .asSequence()
    .filter { it < 3 }
    .onEach { println("filtered $it") }
    .map { it * 10 }
    .forEach { println("final: $it") }

There’s onEach to do what peek does.

Fun fact: Kotlin also wanted to call their sequences “Streams” before it was clear that Java would do the same, so they renamed it to “Sequences”.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement