I recently learned about Stream
s in Java 8 and saw this example:
IntStream stream = IntStream.range(1, 20);
Now, let\'s say th
A Stream is a lazy evaluation mechanism for processing Collections efficiently. This means that all the intermediate operations on the Stream are not evaluated unless necessary for the final (terminal) operation.
In your example, the terminal operation is firstFirst()
. This means the Stream will evaluate the pipeline of intermediate operations until it finds a single int that results from passing the input Stream through all the intermediate operations.
The second filter only receives ints that pass the first filter, so it only processes the numbers 3,6,9,12,15 and then stops, since 15 passes the filter, and supplies the findFirst()
operation the only output it needs.
The first filter will only process ints of the input Stream as long as the terminal operation still requires data, and therefore it will only process 1 to 15.
Well, the thing to understand about streams is that, unlike lists, they don't (necessarily) hold all the items but rather compute each item at a time (lazy evaluation).
It means that when you did IntStream stream = IntStream.range(1, 20);
you didn't actually create a collection with 20 items. You created a dynamically computed collection. Each call to this stream's next
will compute the next item. The rest of the items are still "not there" (sort of speaking).
Same goes for the filter.
When you add the filter that's checking division by 3 you'll get a new stream that's combined of 2 computations - the first one returns the numbers from 1 until it gets to 20, the second computation returns the numbers that are divided by 3. It's important to understand that each time only the first item is calculated. That's why when you added the check for division by 5 it only worked on those items that were divisible by 3. Same goes as to why the printing stopped at 15. The findFirst
method returns the first number that passes all 3 computations (the 1-20 range computation, the division by 3 computation and the division by 5 computation).