1Z0-819 · Question #173
Given: ``java import java.util.ArrayList; import java.util.Arrays; public class TestMe { public static void main(String[] args) { String[] fruitNames = {"apple", "orange", "grape", "lemon"…
The correct answer is A. watermelonorangegrapelemonapricotapple. Option A is correct because the lambda (var a, var b) -> -a.compareTo(b) negates the natural compareTo result, reversing the sort from ascending to descending alphabetical order. The natural order would be apple, apricot, grape, lemon, orange, watermelon, so the reversed output…
Question
import java.util.ArrayList;
import java.util.Arrays;
public class TestMe {
public static void main(String[] args) {
String[] fruitNames = {"apple", "orange",
"grape", "lemon", "apricot", "watermelon"};
var fruits = new ArrayList<>(Arrays.asList(fruitNames));
fruits.sort((var a, var b) -> -a.compareTo(b));
fruits.forEach(System.out::println);
}
}
What is the result?Options
- Awatermelonorangegrapelemonapricotapple
- Bappleapricotgrapefruit
- Cappleapricotgrapelemonorangewatermelon
- Dlemonappleapricotgrapefruit
How the community answered
(63 responses)- A70% (44)
- B16% (10)
- C5% (3)
- D10% (6)
Explanation
Option A is correct because the lambda (var a, var b) -> -a.compareTo(b) negates the natural compareTo result, reversing the sort from ascending to descending alphabetical order. The natural order would be apple, apricot, grape, lemon, orange, watermelon, so the reversed output is watermelon, orange, lemon, grape, apricot, apple - exactly what A shows (the choice text omits line breaks, but println prints each word on its own line).
Option C is wrong because it shows ascending alphabetical order - what you'd get without the negation, i.e., a.compareTo(b) instead of -a.compareTo(b). Options B and D are immediately disqualified because they contain "grapefruit," which is not in the original array at all.
Memory tip: Think of the - before compareTo as a "flip switch" - it inverts the comparison result, which inverts the sort direction. If you see -a.compareTo(b), just reverse the alphabetical order you'd normally expect.
Topics
Community Discussion
No community discussion yet for this question.