15

Java 8 Streams are powerful but when parallelism is not needed Kotlin Sequence seems to be simpler to use.

Is there a way to convert a stream.sequencial() into a Sequence?

atok
  • 5,880
  • 3
  • 33
  • 62
  • an example of this is also mentioned under "Staying Lazy" part of http://stackoverflow.com/questions/35721528/how-can-i-call-collectcollectors-tolist-on-a-java-8-stream-in-kotlin/35722167#35722167 – Jayson Minard May 09 '16 at 18:34

2 Answers2

18

You can get an iterator from a stream and then wrap the iterator into a Sequence:

Sequence { stream.iterator() }

UPD: Starting from Kotlin 1.1 you can use Stream.asSequence() extension (see Michael Richardson's answer), which does the exact same thing as above. The extension is also available for the specialized streams: IntStream, LongStream and DoubleStream.

It is located in kotlin.streams package in kotlin-stdlib-jdk8 library (Kotlin 1.2 and above) or in kotlin-stdlib-jre8 library (Kotlin 1.1 only, deprecated in Kotlin 1.2 and above).

Ilya
  • 21,871
  • 8
  • 73
  • 92
  • 3
    Great! I see there is also Iterator.asSequence() so I can say: stream.iterator().asSequence() – atok Apr 27 '16 at 15:06
  • 4
    Yes, it's almost the same. The difference here is when the `iterator()` function is invoked on Stream, immediately (`asSequence()`) or lazily (`Sequence { }`). – Ilya Apr 27 '16 at 18:03
9

Kotlin has an extension method asSequence() to convert a Java stream to a Kotlin Sequence. In my experience it was not discoverable until I added an import statement:

import kotlin.streams.*

Then simply use as expected:

val seq = stream.asSequence()
Michael Richardson
  • 4,213
  • 2
  • 31
  • 48