Convert Iterable or Iterator to Stream in Java

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 the Iterable but the actual iteration won’t happen until a terminal operation is executed.
  • The second argument in StreamSupport.stream() determines if the resulting Stream should be parallel or sequential. Set it true for a parallel stream and false for a 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 it explicitly. Rather it uses a Predicate to decide 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 the comments.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode