What is an “escape-hatch operation” in a Java stream?

From the javadoc of the stream package:

In almost all cases, terminal operations are eager, completing their
traversal of the data source and processing of the pipeline before
returning. Only the terminal operations iterator() and spliterator()
are not; these are provided as an “escape hatch” to enable arbitrary
client-controlled pipeline traversals in the event that the existing
operations are not sufficient to the task.

Which means that in most cases the stream traversal is complete when a terminal operation returns, but not in the case of iterator() and spliterator(): by using one of these terminal operations an Iterator or a Spliterator is returned, but the pipeline is still “open” and it will be processed as the elements are requested through the iterator. This way the stream processing becomes lazy, because the operations on the stream are only executed if the next element is requested.

Iterator<Person> iterator = persons
    .stream()
    .filter(p -> !p.getName().equals("Mike Tyson"))
    .iterator();

After the iterator() method is called, the stream is “terminated”: you cannot chain more methods. But you can access the elements of the stream by calling the next() method of the returned iterator and the stream will start to be processed only the first time you do this. And this is true only if the iterator() or thespliterator() terminal operation is used.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)