As simple as:
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
Long x = Stream.of(1, 2, 3).map(i -> {
System.out.println(i);
return i + 4;
}).count();
System.out.println(x); // prints '3'
}
}
The count()
here is used in order to trigger the intermediate operations which include System.out.println(i)
, but nothing gets printed from inside map()
. Why is that?
The javadoc for count() has note that:
An implementation may choose to not execute the stream pipeline (either sequentially or in parallel) if it is capable of computing the count directly from the stream source. In such cases no source elements will be traversed and no intermediate operations will be evaluated.
Streams are lazy and smart. Since your terminal operation is count
, which does not care of individual elements, but only of their number, map
isn't called.
Replace count
with something that would need to calculate individual elements, like sum
- and map
will be called.
Long x = Stream.of(1, 2, 3).map(i -> {
System.out.println(i);
return i + 4;
})
.mapToLong(Long::valueOf)
.sum(); // prints 1 2 3
System.out.println(x); // prints 18
Also a person in comments rightfully reminds you side effects.
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