The important thing you need to understand is that threads are controlled by a terminal operation. The terminal operation determines whether all elements should be processed or any at all. Thus, collect is an operation that processes each element, whereas findAny can stop processing elements after it encounters the corresponding element.
And count() cannot handle any elements at all when it can determine the size of the stream without processing the elements. Since this is an optimization not made in Java 8, but which will be in Java 9, there may be surprises when switching to Java 9 and have code based on count() processing of all elements. It is also associated with other implementation-dependent details, for example, even in Java 9, the reference implementation will not be able to predict the size of the infinite stream source in combination with limit while there is no fundamental restriction to prevent such a prediction.
Because peek allows you to "perform the provided action for each element as the elements are consumed from the resulting stream", it does not require processing of the elements, but it will perform an action depending on what the terminal operation requires. This implies that you should use it with great care if you need specific processing, for example, you want to apply an action to all elements. It works if the terminal operation is guaranteed to handle all elements, but even then you must be sure that not the next developer will not change the terminal operation (or you will forget this subtle aspect).
In addition, while threads guarantee meeting order maintenance for a specific combination of operations, even for parallel threads, these guarantees do not apply to peek . When compiling into a list, the resulting list will have the correct order for ordered parallel threads, but the peek action can be called in arbitrary order and at the same time.
So the most useful thing you can do with peek is to find out if a thread element has been processed, which exactly matches the API documentation:
This method exists mainly to support debugging when you want to see elements when they pass a certain point in the pipeline
Holger Nov 10 '15 at 17:50 2015-11-10 17:50
source share