Close Java 8 Stream -


if use java 8 stream list.stream().filter(....).collect(..)..... when closed stream?

is practice close stream next example?

stream<string> stream = list.stream(); string result = stream.limit(10).collect(collectors.joining("")); stream.close(); 

it not necessary close streams @ all. need close streams use io resources.

from stream documentation:

streams have basestream.close() method , implement autocloseable, stream instances not need closed after use. generally, streams source io channel (such returned files.lines(path, charset)) require closing. streams backed collections, arrays, or generating functions, require no special resource management. (if stream require closing, can declared resource in try-with-resources statement.)

if need close stream, best practice use try-with-resources statement:

try ( stream<string> stream = files.lines(path, charset) ) {     // } 

Comments