Close

Java 8 Streams - Stream.onClose Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.BaseStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamLogicBig

Method:

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.


Examples


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();
}
}

Output

one
two
three
four
-- going to close --
-- closing stream --




See Also