Core Java

Java Iterator to Java 8 Stream

Sometimes during my work, I need to integrate with other libraries which they return an Iterator object instead of a list. This is fine from the point of view of libraries but it might be a problem when you want to use Java 8 streams on the returned iterator. There is one way to transform the Iterator to Iterable and then easily to stream.

Since all the time I need to remember how to do it, I decided to share the snippet here.

Iterator<JsonValue> iterator = elements.iterator();
Iterable<JsonValue> valueIterable = () -> iterator;

List<String> StreamSupport.stream(valueIterable.spliterator(), false)
                .map(element -> element.asString())
.collect(Collectors.toList());

In the example, first of all, we have an Iterator class. Since Iterator cannot be used as a stream but an Iterable can do, we just create a new Iterable class which overrides its iterator() method to return the Iterator we want to stream.

Then we have an Iterable which is not streamable yet. So what we need to do is to use StreamSupport class to convert the Iterable to a Stream.

And that’s all then you can use all streaming operations without any problem.

We keep learning,

Alex.

Published on Java Code Geeks with permission by Alex Soto, partner at our JCG program. See the original article here: Java Iterator to Java 8 Stream

Opinions expressed by Java Code Geeks contributors are their own.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button