[JAVA] [Small story] Convert Stream to Iterable

How to do

Use Files # write (Path, Iterable <? Extends CharSequence> lines, OpenOption ...) as an example.

Stream<String> stream = Stream.of("foo", "bar", "baz");
Iterable<String> iterable = stream::iterator;
Files.write(Paths.get("test.txt"), iterable);

Or

Stream<CharSequence> stream = Stream.of("foo", "bar", "baz");
Files.write(Paths.get("test.txt"), stream::iterator);

By the way

Stream<String> stream = Stream.of("foo", "bar", "baz");
//Compile error
Files.write(Paths.get("test.txt"), stream::iterator);
//This will pass
Files.write(Paths.get("test.txt"), (Iterable<String>)stream::iterator);

Background and notes

Stream / BaseStream has a method called ʻiterator () but does not implement Iterable. The reason seems to be that ʻIterable # iterator () can be called repeatedly. Iterator is returned to the document of [ʻIterable # iterator () ](https://docs.oracle.com/javase/jp/8/docs/api/java/lang/Iterable.html#iterator--) Only that is written, but [BaseStream # iterator ()`](https://docs.oracle.com/javase/jp/8/docs/api/java/util/stream/BaseStream.html#iterator -) Clearly states that it is a termination operation, that is, it can only be called once. Reference: Why is Stream not an Iterable ?

Therefore, keep in mind that if you easily pass the conversion by the above method to a class that uses Iterable, a runtime exception may occur depending on the implementation.

Recommended Posts

[Small story] Convert Stream to Iterable
I learned stream (I want to convert List to Map <Integer, List>)
Convert 2D array to csv format with Java 8 Stream API
Convert an array that may be null to a stream
Convert Java Powerpoint to XPS
I want to convert characters ...
Convert String type to Timestamp type
Convert to Ruby Leet string
Convert Serializable Object to byte []
Convert from ○ months to ○ years ○ months
[Java] Introduction to Stream API
How to convert Java radix
[Java] Convert ArrayList to array