Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does collect operation on Stream close the stream and underlying resources?

Tags:

Does below code need to be wrapped in try-with-resources to make sure underlying file is closed?

List<String> rows = Files.lines(inputFilePath).collect(Collectors.toList()); 
like image 414
Sagar Avatar asked Jul 01 '15 20:07

Sagar


People also ask

Does collect close stream?

So yes, wrap the Stream returned by lines in a try-with-resources statement. (Or close it appropriately.)

How does stream collect work?

Stream. collect() is one of the Java 8's Stream API's terminal methods. It allows us to perform mutable fold operations (repackaging elements to some data structures and applying some additional logic, concatenating them, etc.) on data elements held in a Stream instance.

Which method is used to close a stream?

close() method is used to close the writer. close() flushes and then closes the stream.

Which of the following method will close the stream pipeline and return a result?

Operations that close a stream pipeline are called terminal operations.


2 Answers

There is a trick to make the Stream implementation calling close() after the terminal operation:

List<String> rows = Stream.of(Files.lines(inputFilePath)).flatMap(s->s)                    .collect(Collectors.toList()); 

It simply creates a stream encapsulating the stream of lines as a single item and uses flatMap with an identity function (Function.identity() would work as well) to turn it into a stream of lines again.

The interesting point is a property of Stream.flatMap(…):

Each mapped stream is closed after its contents have been placed into this stream.

So the code above will close the stream of lines. While it looks more concise it has the disadvantage over try with resources that current implementation of flatMap lacks lazy evaluation which is not relevant here as you are collecting all lines into a list anyway. But it’s something to keep in mind when using this trick in other scenarios.


For the question’s code as-is there is an even simpler solution:

List<String> rows = Files.readAllLines(inputFilePath); 

Reads all lines and closes all resources…

like image 181
Holger Avatar answered Sep 24 '22 23:09

Holger


As the javadoc of the overloaded Files#lines(Path, Charset) method states

The returned stream encapsulates a Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

So yes, wrap the Stream returned by lines in a try-with-resources statement. (Or close it appropriately.)

like image 30
Sotirios Delimanolis Avatar answered Sep 23 '22 23:09

Sotirios Delimanolis