Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was reading the Java docs and encountered this sentence:

Except for the escape-hatch operations iterator() and spliterator(), execution begins when the terminal operation is invoked, and ends when the terminal operation completes.

I am not sure what "escape-hatch operations" means. Could someone please explain this term?

like image 399
Mehraj Malik Avatar asked Mar 01 '17 06:03

Mehraj Malik


1 Answers

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.

like image 163
DVarga Avatar answered Oct 03 '22 23:10

DVarga