Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium

Question 42

Question ID: UKOCP42910


Given code:


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

a

d

bb

mm

www

zzz

  • A No need to make any changes, on execution given code prints expected result
  • B Replace stream.sorted(lengthComp) with stream.sorted(lengthComp.thenComparing(String::compareTo))
  • C Replace stream.sorted(lengthComp) with stream.sorted(lengthComp.reversed())
Reveal correct answer

Correct answer: B

Explanation

UKOCP42910:

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(lengthComp) 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