Java 8 Streams and try with resources

前端 未结 4 1359
自闭症患者
自闭症患者 2020-12-10 10:29

I thought that the stream API was here to make the code easier to read. I found something quite annoying. The Stream interface extends the java.lang.AutoC

4条回答
  •  粉色の甜心
    2020-12-10 11:13

    You only need to close Streams if the stream needs to do any cleanup of itself, usually I/O. Your example uses an HashSet so it doesn't need to be closed.

    from the Stream javadoc:

    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.

    So in your example this should work without issue

    List collect = photos.stream()
                           .map(photo -> ...)
                           .collect(toList());
    

    EDIT

    Even if you need to clean up resources, you should be able to use just one try-with-resource. Let's pretend you are reading a file where each line in the file is a path to an image:

     try(Stream lines = Files.lines(file)){
           List collect = lines
                                      .map(line -> new ImageView( ImageIO.read(new File(line)))
                                      .collect(toList());
      }
    

提交回复
热议问题