Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream to file [duplicate]

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.

like image 369
knub Avatar asked Aug 17 '15 15:08

knub


People also ask

How do I find duplicates in a string in java 8?

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() .

What is the function used to duplicate a 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.

How do I filter duplicates in java 8?

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.

How do you reuse a stream in java?

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.


1 Answers

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.

like image 62
Tagir Valeev Avatar answered Sep 19 '22 19:09

Tagir Valeev