Terminal operators do NOT close the stream automatically. Consider this code:
Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Closed"));
list.forEach(System.out::println);
This does NOT print "Closed".
However, the following does print "Closed":
try (Stream<Path> list = Files.list(directory).onClose(() -> System.out.println("Closed"))) {
list.forEach(System.out::println);
}
So the best way to do it is to use the try-with-resources mechanism.