I was reading the Java docs and encountered this sentence:
Except for the escape-hatch operations
iterator()
andspliterator()
, 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?
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()
andspliterator()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With