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);
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
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