Suppose I have a java.util.stream.Stream
of objects with some nice toString
method: What's the shortest/most elegant solution to write this stream to a file, one line per stream element?
For reading, there is the nice Files.lines
method, so I thought there must be a symmetric method for writing to file, but could not find one. Files.write
only takes an iterable.
In Java 8 Stream, filter with Set. Add() is the fastest algorithm to find duplicate elements, because it loops only one time. Set<T> items = new HashSet<>(); return list. stream() .
CopyTo(Stream) Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.
You can use the Stream. distinct() method to remove duplicates from a Stream in Java 8 and beyond. The distinct() method behaves like a distinct clause of SQL, which eliminates duplicate rows from the result set.
From the documentation: A stream should be operated on (invoking an intermediate or terminal stream operation) only once. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. So the answer is no, streams are not meant to be reused.
Probably the shortest way is to use Files.write
along with the trick which converts the Stream
to the Iterable
:
Files.write(Paths.get(filePath), (Iterable<String>)stream::iterator);
For example:
Files.write(Paths.get("/tmp/numbers.txt"), (Iterable<String>)IntStream.range(0, 5000).mapToObj(String::valueOf)::iterator);
If it looks too hackish, use more explicit approach:
try(PrintWriter pw = new PrintWriter(Files.newBufferedWriter( Paths.get("/tmp/numbers.txt")))) { IntStream.range(0, 5000).mapToObj(String::valueOf).forEach(pw::println); }
If you have stream of some custom objects, you can always add the .map(Object::toString)
step to apply the toString()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With