Close Java 8 Stream

前端 未结 3 1419
天命终不由人
天命终不由人 2020-12-01 07:26

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

3条回答
  •  渐次进展
    2020-12-01 08:04

    I have to add that by default streams are not closed at all!

    List list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    
    // "--" is not printed at all:
    list.stream().onClose(()->System.out.println("--")).forEach(x -> System.out.println(x));
    
    System.out.println("with try(){}:");
    
    // "--" is printed:
    try (Stream stream = list.stream() ) {
        stream.onClose(() -> System.out.println("--")).forEach(x -> System.out.println(x));
    }
    

提交回复
热议问题