Sorting and Comparators
Collections.sort and List.sort use natural order or a Comparator.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> w = new ArrayList<>(List.of("pear", "fig", "apple"));
Collections.sort(w);
System.out.println(w);
w.sort(Comparator.comparing(String::length));
System.out.println(w);
}
}Result
[apple, fig, pear] [fig, pear, apple]
Exercise
Sort by length.
Comparator.(String::length)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.