tl;dr
Just cast, no need to convert.
Cast Stream<String>::iterator
to Iterable<String>
.
Details
CAUTION See Answer by Holger explaining dangers of using a stream-backed Iterable
.
Yes, you can make an Iterable
from a Stream
.
The solution is simple, but not obvious. See this post on Maurice Naftalin's Lambda FAQ.
The signature of the iterator
method of BaseStream
(superclass of Stream
) returning a Iterator
matches the only method of the functional interface Iterable
, so the method reference Stream<T>::iterator
can be used as an instance of Iterable<T>
. (The fact that both methods have the same name is coincidental.)
Make your input.
String input = "this\n" +
"that\n" +
"the_other";
Stream<String> stream = input.lines() ;
Use the method reference to generate a Iterable<String>
.
Iterable< String > iterable = stream::iterator;
Test the results.
for ( String s : iterable )
{
System.out.println( "s = " + s );
}
See this code run live at IdeOne.com.
s = this
s = that
s = the_other
CAVEAT Beware of the risk of stream-backed Iterable
. Explained in the correct Answer by Holger.