Java 8 Streams Java Java API
java.util.stream.BaseStream
S onClose(Runnable closeHandler)
This intermediate operation returns an equivalent stream with an additional close listener registered with the stream. Close handlers are run when the BaseStream#close() method is called on the stream, and are executed in the order they were added.
package com.logicbig.example.stream;import java.util.Arrays;import java.util.stream.Stream;public class OnCloseExample { public static void main(String... args) { String[] s = {"one", "two", "three", "four"}; Stream<String> stream = Arrays.stream(s).onClose(() -> { System.out.println("-- closing stream --"); }); stream.forEach(System.out::println); System.out.println("-- going to close --"); stream.close(); }}
onetwothreefour-- going to close ---- closing stream --