Page 1 of 1

About Question enthuware.ocpjp.v8.2.1901 :

Posted: Fri Mar 13, 2020 2:57 am
by lerato
In need of help on the following question ?
Given:
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17); //1
Stream<Integer> primeStream = primes.stream(); //2

Predicate<Integer> test1 = k->k<10; //3

the given answer on the enthuware mockExam says the correct answer is as follows .

primeStream.collect(Collectors.partitioningBy(test1,Collectors.counting())).values().forEach(System.out::print)

can you make a method call like values() on a terminal operator like the callect() method ? does it even compile ?

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

Posted: Fri Mar 13, 2020 3:11 am
by admin
What happened when you tried to compile/run it?
values() returns a new Stream and you can certainly process the elements of that stream using forEach.

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

Posted: Fri Oct 23, 2020 4:37 am
by RogierA
why are the values switched in the last (correct) option? from 4 then 3, to 3 then 4.

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

Posted: Fri Oct 23, 2020 6:01 am
by admin
Since you are passing Collectors.partitioningBy to primeStream.collect, the result is actually a map containing key value pairs (true,4) and (false, 3). Now, when you call values().forEach on this map, the order of the values returned is implementation dependent (i.e. depends on the implementation of the map generated by the collect method). In this case, it returns 3, 4 but some other implementation may return 4, 3.