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?
Using Collectors. Get the Stream to be converted. Collect the stream as List using collect() and Collectors. toList() methods. Convert this List into an ArrayList.
A sequence is a container Sequence<T> with type T. It's also an interface, including intermediate operations like map() and filter(), as well as terminal operations like count() and find(). Like Streams in Java, Sequences in Kotlin execute lazily.
Streams come from Java, where there are no inline functions, so Streams are the only way to use these functional chains on a collection in Java. Kotlin can do them directly on Iterables, which is better for performance in many cases because intermediate Stream objects don't need to be created.
The Collector class is used to collect the elements of the Stream into a collection. This class has the toList() method, which converts the Stream to a List.
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).
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With