Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

How can I turn an Iterator into an Iterable?

It’s pretty simple to do this with a lambda. However, one should be cautious because the resulting Iterable doesn’t fulfil
the usual expectation that it’s possible to get multiple, independent Iterator instances by calling the iterator()
method more than once.

Given an Iterator, one can create an Iterable instance as follows:

Iterator<String> iterator = ... ;
Iterable<String> iterable = () -> iterator;

The resulting Iterable can be used to produce a single, working Iterator. Subsequent calls to
the iterator() method will return the same Iterator instance, which may have
been exhausted, or otherwise be in some indeterminate state.

One can use this technique directly in the enhanced-for (“for-each”) loop. However, it requires
a cast to establish the target type for the lambda:

for (String s : (Iterable<String>)() -> iterator) {
    ...
}