Skip to content

Kotlin Stream peek(…) method

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

Seems there are no alternative intermediate operations:

I found only terminating forEach(…)


The Stream alternative in Kotlin is Sequences.

 listOf(1, 2, 3, 4, 5)
    .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”.