I think that the explanation is wrong :
If you append a terminal operation such as count(), [for example, ls.stream().map(func).peek(System.out::print).count(); ], it will print 149.
When using the count() operation on a Stream , if there are no other intermediate operation who can change the number of elements of the Stream( example : filter .. ) , the count operation will execute directly on the source of Stream and no intermediate operation will be executed .
List<Integer> ls = Arrays.asList(1, 2, 3);
Function<Integer, Integer> func = a->a*a; //1
ls.stream().map(func).peek(System.out::print).count(); //2 //will run but will not print anything
map operation has no effect on the number of elements of the Stream ,so it will be never executed
?
About Question enthuware.ocpjp.v8.2.1799 :
Moderator: admin
-
- Posts: 3
- Joined: Mon Mar 29, 2021 6:33 am
- Contact:
-
- Site Admin
- Posts: 10046
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v8.2.1799 :
Actually, the explanation is correct but the example of count is incorrect because of how the implementation of count is done by the Java library. The explanation has now been updated to:
thank you for your feedback!
So, count() does not generate the output as mentioned because of how the library is implemented. Another JDK library may chose not to short circuit the stream pipe line, which case the output will be as expected.If you append a terminal operation such as min(), [for example, /// ls.stream().map(func).peek(System.out::print).min( (a, b)->a-b); ///], it will print 149.
Note that count() is also a terminal operation but it may short circuit the stream pipeline, which means, 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.
thank you for your feedback!
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 78 guests