Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 42
Question ID: UKOCP42910
Given code:
- package com.udayankhattry.ocp;
- import java.util.Comparator;
- import java.util.stream.Stream;
- public class Test {
- public static void main(String[] args) {
- Stream<String> stream = Stream.of("d", "a", "mm", "bb", "zzz", "www");
- Comparator<String> lengthComp = (s1, s2) -> s1.length() - s2.length();
- stream.sorted(lengthComp).forEach(System.out::println);
- }
- }
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)withstream.sorted(lengthComp.thenComparing(String::compareTo)) -
C
Replace
stream.sorted(lengthComp)withstream.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.
