Importing java dot util, star, brings in the whole package. Collections dot sort sorts alphabetically. Reverse order flips it. Comparing, with string colon colon length, sorts by length. The double colon is a method reference. We'll explain it in module twelve. Then comparing breaks ties, alphabetically. Run it. Each line shows a different order. Notice fig, and kiwi, swap places in the last line.
Main.javajava
import java.util.*;public class Main { public static void main(String[] args) { List<String> fruit = new ArrayList<>(List.of("pear", "fig", "banana", "kiwi")); Collections.sort(fruit); System.out.println("A to Z: " + fruit); fruit.sort(Comparator.reverseOrder()); System.out.println("Z to A: " + fruit); fruit.sort(Comparator.comparing(String::length)); System.out.println("By length: " + fruit); fruit.sort(Comparator.comparing(String::length) .thenComparing(Comparator.naturalOrder())); System.out.println("Then A-Z: " + fruit); }}
Output
A to Z: [banana, fig, kiwi, pear]
Z to A: [pear, kiwi, fig, banana]
By length: [fig, pear, kiwi, banana]
Then A-Z: [fig, kiwi, pear, banana]
Here's a small record, Person, with a name and an age. Comparing person age sorts by age. Reversed flips that, and then comparing name breaks ties. Run it. Youngest first. Then oldest first, with Mia before Zoe, because they're both thirty one.
Main.javajava
import java.util.*;public class Main { record Person(String name, int age) {} public static void main(String[] args) { List<Person> people = new ArrayList<>(List.of( new Person("Zoe", 31), new Person("Adam", 25), new Person("Mia", 31))); people.sort(Comparator.comparing(Person::age)); System.out.println(people); people.sort(Comparator.comparing(Person::age).reversed() .thenComparing(Person::name)); System.out.println(people); }}
Collections dot sort uses natural order. A comparator sorts by any field, can be reversed, and can break ties. Next, removing items safely, while looping.