Learn to convert Iterable
or Iterator
to Stream
. It may be desired at times when we want to utilize excellent support of lambda expressions and collectors in Java Stream API.
1. Converting Iterable to Stream
The Iterables are useful but provide limited support for lambda expressions added in Java 8. To utilize full language features, it is desired to convert the iterable to stream.
To convert, we will use iterable.spliterator()
method to get the Spliterator reference, which is then used to get the Stream
using StreamSupport.stream(spliterator, isParallel)
method.
//Iterable Iterable<String> iterable = Arrays.asList("a", "b", "c"); //Iterable -> Stream //false means sequential stream Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false);
- The above code is only linking the
Stream
to theIterable
but the actual iteration won’t happen until a terminal operation is executed. - The second argument in
StreamSupport.stream()
determines if the resultingStream
should be parallel or sequential. Set ittrue
for a parallel stream andfalse
for sequential stream.
2. Converting Iterator to Stream – Java 8
The Iterator to Stream conversion follows the same path as Iterable to Stream.
The only difference is that the Iterator
interface has no spliterator()
method so we need to use Spliterators.spliteratorUnknownSize()
method to get the spliterator
. Rest everything is same.
// Iterator Iterator<String> iterator = Arrays.asList("a", "b", "c") .listIterator(); //Extra step to get Spliterator Spliterator<String> splitItr = Spliterators .spliteratorUnknownSize(iterator, Spliterator.ORDERED); // Iterator -> Stream Stream<String> stream = StreamSupport.stream(splitItr, false);
3. Converting Iterator to Stream – Java 9
Java 9 has made the syntax a little easier and now we don’t need to use Spliterator
explicitly. Rather it uses a Predicate
to decide until when the elements shall be taken.
// Iterator Iterator<String> iterator = Arrays.asList("a", "b", "c") .listIterator(); Stream<String> stream = Stream.generate(() -> null) .takeWhile(x -> iterator.hasNext()) .map(n -> iterator.next());
Drop me your questions in comments.
Happy Learning !!