Back to questions
JuniorTheoryCommon
What does the program print?
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> ws = new ArrayList<>(
List.of("pear", "banana", "fig", "apple"));
ws.sort(Comparator.comparing(String::length).reversed());
System.out.println(ws);
}
}[banana, apple, pear, fig]
- Expecting
[fig, pear, apple, banana]:reversed()returns a comparator with the opposite order, so the longest word comes first. - Expecting the list unchanged:
ws.sort(c)sorts the list in place and returns nothing, so there is no copy to lose.
- How would you also sort words of equal length alphabetically?
- Why does
Comparator.comparing(w -> w.length()).reversed()not compile?