Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard

Question 50

Given code of Test.java file: 

Which of the following needs to be done, so that output is: 

a
d
bb
mm
www
zzz

  • A

    Replace stream.sorted(lengthComp)  with stream.sorted(lengthComp.thenComparing(String::compareTo)) 

  • B

    Replace stream.sorted(lengthComp)  with stream.sorted(lengthComp.reversed()) 

  • C No need to make any changes, on execution given code prints expected result.
Reveal correct answer

Correct answer: A

Explanation

Current code displays below output:

d

a

mm

bb

zzz

www


if string's length is same, then insertion order is preserved.


Requirement is to sort the stream in ascending order of length of the string and if length is same, then sort on natural order.


lengthComp is for sorting the string on the basis of length, thenComparing default method of Comparator interface allows to pass 2nd level of Comparator.

Hence replacing 'stream.sorted()' with 'stream.sorted(lengthComp.thenComparing(String::compareTo))' will do the trick.


stream.sorted(lengthComp.reversed()) will simply reversed the order, which means longest string will be printed first, but this is not expected.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need