Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert java.util.stream.Stream<Something> into kotlin.Sequence<Something>

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?

like image 952
atok Avatar asked Apr 27 '16 14:04

atok


People also ask

Can we convert stream to list in Java?

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.

What is a kotlin Sequence?

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.

Should I use streams in Kotlin?

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.

Which method is used to convert stream to list?

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.


2 Answers

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).

like image 159
2 revs Avatar answered Oct 16 '22 18:10

2 revs


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()
like image 8
Michael Richardson Avatar answered Oct 16 '22 18:10

Michael Richardson