Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 39
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.Arrays;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- public class Test {
- public static void main(String[] args) {
- List<String> list = Arrays.asList("#####", "#", "##", "####", "###");
- Comparator<String> comp = Comparator.comparing(s -> s);
- Collections.sort(list, comp.reversed());
- printCodes(list);
- }
- private static void printCodes(List<String> list) {
- for (String str : list) {
- System.out.println(str);
- }
- }
- }
What will be the result of compiling and executing Test class?
-
A
#####
#
##
####
### -
B
#####
####
###
##
# -
C
#
##
###
####
##### -
D
###
####
##
#
#####
Reveal correct answer
Correct answer: B
Explanation
Comparator.comparing(s -> s); compares the passed Strings only. As all the characters in the String are '#', this means strings are sorted on the basis of their lengths.
Comparator referred by comp sorts on the basis of strings' lengths.
Default reversed() method just reverses the ordering of the Comparator referred by comp, which means sorts the strings in descending order of their lengths.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
