import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
Stream.of(1, 2, 3).map(i -> {
System.out.println(i+":inside map");
return i+4;
}).forEach(t->System.out.println(t + ":inside foreach"));
}
}
// Prints:
1:inside map
5:inside foreach
2:inside map
6:inside foreach
3:inside map
7:inside foreach
Shouldn't the output be :
1:inside map
2:inside map
3:inside map
5:inside foreach
6:inside foreach
7:inside foreach
I was under the impression that after each intermediate operation ends, it returns a new stream. So foreach should have gotten (5,6,7) and therefore print
5:inside foreach
6:inside foreach
7:inside foreach
But the case shows that foreach is executed for each entry of map one by one. Why is that?
That's because map()
is indeed an intermediate operation, but it's also a stateless one. From the docs (https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps):
Intermediate operations are further divided into stateless and stateful operations. Stateless operations, such as filter and map, retain no state from previously seen element when processing a new element -- each element can be processed independently of operations on other elements. Stateful operations, such as distinct and sorted, may incorporate state from previously seen elements when processing new elements.
Meaning that whenever your element is mapped to a new one, it can immediately be processed by the rest of the pipeline, without the need to wait for all the elements to be mapped first. That's obviously an over-simplification, but I just wanted to explain the general idea.