Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

How can I turn an Iterator or an Iterable into a Stream?

Iterator

Turning an Iterator into a Stream is a bit involved. First, you turn the Iterator into a Spliterator. Second, you turn that Spliterator into a Stream. For example, this turns an Iterator iterator into an ordered, sequential stream:

StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);

The reason for this two-step process is that there are options you need to supply that don’t have good defaults. The example shows the creation of an ordered Spliterator. You might instead want to create an unordered Spliterator, which may give a performance advantage in some cases. (More precisely, although the elements will come out of the Iterator in some order, that order might not have any meaning. In that case we say it is unordered. An example is an Iterator that is backed by a HashSet.)

The second step converts the Spliterator into a Stream, and it offers the option to make the resulting Stream run sequentially or in parallel.

Iterable

It’s a bit easier to turn an Iterable into a Stream. Iterable has a default method spliterator(), so you can use that to get a Spliterator, which you can then convert to a Stream:

StreamSupport.stream(iterable.spliterator(), false);