Return to site


· java,ocp

Your colleague is working on an application that must find a most-frequently-used word in a Stream〈String〉,

and each element of that stream is a single word.

The stream is provided by the reference strm.

Which of these pipeline expressions can perform this task? Choose two.

* Option 'descending identity'

* Option 'ascending string lambda'

* Option 'method reference in sorted'

* Option 'comparator type mismatch'

* Option 'odd variable name'

#java #certificationquestion #ocp

Answer: Option 'descending identity' & option 'odd variable name' are right.

Option 'descending identity' is a correct implementation of this approach.

The first argument to the groupingBy factory method should be a function that takes the stream object and returns the key.

And Function.identity() is ok with that.

The second argument is the counting factory, and that’s exactly what was described above.

Next, the sorting is performed using Comparator explicitly coded as a lambda.

The effect is to compare the value of the two entry objects, but because the code is written as e2 … compareTo … e1, the ordering will be reversed (descending).

Option 'ascending string lambda' is incorrect.

It is syntactically valid but the stream is sorted in ascending order.

Therefore, it will return an entry with a least-frequently used word.

Option 'method reference in sorted' is incorrect.

It does not compile, sorted() expect a comparator and the method reference: Map.Entry::comparingByValue as argument does not compile.

Option 'comparator type mismatch' is incorrect, Collectors.counting() returns a Long and the return type of a Comparator is int.

So the part '.sorted(( e1,e2 )->e2.getValue()-e1.getValue())' does not compile.

Option 'odd variable name' is correct.

It compiles even if the '___' as variable name is odd (and should not be used in real code).