Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 50
Given code of Test.java file:
- package com.udayan.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
Replace
stream.sorted(lengthComp)withstream.sorted(lengthComp.thenComparing(String::compareTo)) -
B
Replace
stream.sorted(lengthComp)withstream.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.
