Java
Programming
Iterator
Stream
Code Conversion

How to convert an Iterator to a Stream?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Java, both Iterator and Stream are interfaces that provide a means of processing sequences of elements, but they do it in fundamentally different ways. An Iterator is an older, pre-Java 8 interface that enables you to traverse through a collection of elements one by one. On the other hand, Stream is a modern, functional programming construct introduced in Java 8, which supports a more expressive and less error-prone approach to processing sequences of elements, especially with its rich API supporting operations such as map, reduce, filter, and more.

Converting an Iterator to a Stream

There are several ways to convert an Iterator to a Stream. Below are some of the methods illustrating how this can be accomplished:

Using Spliterators and StreamSupport

One practical approach involves using the Spliterators utility class, which provides a set of implementations for creating and manipulating spliterator objects. Here’s how you can use it along with the StreamSupport class:

java
1import java.util.*;
2import java.util.stream.*;
3
4Iterator<String> iterator = Arrays.asList("a", "b", "c").iterator();
5Stream<String> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);
6stream.forEach(System.out::println); // Outputs: a b c

Here, Spliterators.spliteratorUnknownSize is used to create a spliterator over the elements of the given iterator, where the size of the spliterator is unknown. The second parameter in the spliteratorUnknownSize method defines the characteristics of the spliterator (e.g., Spliterator.ORDERED indicates that the elements are ordered). The boolean parameter in StreamSupport.stream determines whether the stream is to be used in parallel (true) or sequentially (false).

Iterating and Collecting

If you are not concerned about lazily processing the stream and just want a quick way to turn an iterator into a stream, collecting elements from the iterator into a list and then creating a stream from that list is a straightforward approach:

java
1Iterator<String> iterator = Arrays.asList("x", "y", "z").iterator();
2List<String> list = new ArrayList<>();
3iterator.forEachRemaining(list::add);
4Stream<String> stream = list.stream();
5stream.forEach(System.out::println); // Outputs: x y z

This method has an overhead of storing all elements in a list before streaming, which might not be efficient for large data sets.

When to Use Each Method

  • Use Spliterators and StreamSupport: When you need a lazy evaluation and want to avoid storing all elements in memory. This is suitable for handling large datasets.
  • Collecting into a List: When you want simplicity and the dataset is not prohibitively large.

Table: Methods Summary

MethodUse CaseAdvantagesDisadvantages
Spliterators with StreamSupport.streamLarge datasets; Need stream operations.Efficient memory usage; Lazy processing.Slightly more complex implementation.
Iterating and Collecting into a ListSmall to moderate datasets; Simplicity.Easy to implement.Increased memory usage; Not lazy.

Conclusion

Converting an Iterator to a Stream in Java allows developers to leverage the powerful Stream API for more expressive, functional-style operations. Depending on the context — such as the size of the data and performance considerations — developers can choose between directly using Spliterators along with StreamSupport for memory-efficient, lazy processing or iterating through the Iterator and collecting the results into a list for simplicity and ease of use.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.