About Question enthuware.ocpjp.v8.2.1799 :

All the posts and topics that contain only an error report will be moved here after the error is corrected. This is to ensure that when users view a question in ETS Viewer, the "Discuss" button will not indicate the presence of a discussion that adds no value to the question.

Moderators: Site Manager, fjwalraven

Post Reply
Oussama
Posts: 3
Joined: Mon Mar 29, 2021 6:33 am
Contact:

About Question enthuware.ocpjp.v8.2.1799 :

Post by Oussama »

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
?

admin
Site Admin
Posts: 10384
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocpjp.v8.2.1799 :

Post by admin »

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:
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.
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.

thank you for your feedback!

Post Reply

Who is online

Users browsing this forum: No registered users and 12 guests