If we use Java 8 Stream like list.stream().filter(....).collect(..).....
When is it closed this stream?
Is it good practice that we close the stream us as the next example?
Stream<String> stream = list.stream();
String result = stream.limit(10).collect(Collectors.joining(""));
stream.close();
It is generally not necessary to close streams at all. You only need to close streams that use IO resources.
From the Stream documentation:
Streams have a BaseStream.close()
method and implement AutoCloseable
, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)
) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)
If you need to close a stream, then best practice would be to use the try-with-resources statement:
try ( Stream<String> stream = Files.lines(path, charset) ) {
// do something
}