Do java streams iterate a stream of values multiple times? For example, if we are filtering and then mapping, does the stream iterate once to filter and then iterate again to map? Or does it just filter and map each element as it iterates the stream once?
CodePudding user response:
The latter, each intermediate operation is applied once to every item "flowing" through the stream. It is easy to verify yourself: simply add print statements in each step.
Stream.of(1,2,3,4,5)
.filter(x -> {
System.out.println("Filtering " x);
return x < 4;
})
.map(x -> {
System.out.println("Mapping " x);
return x * 2;
})
.forEach(System.out::println);
Output:
Filtering 1
Mapping 1
2
Filtering 2
Mapping 2
4
Filtering 3
Mapping 3
6
Filtering 4
Filtering 5
"A stream" doesn't exist as a whole. A stream can be infinite. As long as nobody consumes the streams, no values are flowing through the stream. No consumers = no filtering, no mapping. The consumer of a stream is its terminal operation.
Only when the terminal operation is called, the stream takes the first element from its source and feeds it through its step one by one as necessary. Not all elements must arrive at the terminal operation (they could have been filtered out).
Some stream operations need to consume the full stream, before they can pass elements downstream, e.g. sorted
. Sorting is impossible without knowing all the values. But most of the stream operations can operate on single elements and produce 0 or more new elements.