Sorting With Comparators
A Comparator describes an ordering outside the class being sorted. It is useful when a type has several sensible orders.
comparingInt builds a comparator from a numeric property. reversed flips ascending order to descending order.
Choose a sorting rule
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>(
List.of("pear", "watermelon", "fig"));
fruits.sort(Comparator.comparingInt(String::length));
System.out.println(fruits);
fruits.sort(Comparator
.comparingInt(String::length)
.reversed());
System.out.println(fruits);
}
}
Output:
[fig, pear, watermelon]
[watermelon, pear, fig]
String::length is a method reference. It tells comparingInt to call length() on each fruit and compare the numbers it gets back, so shorter names come first. Adding .reversed() to the same comparator puts the longest name first.
A comparator should be consistent and transitive. Contradictory comparisons can make sorting fail or behave unpredictably.
Sort Player objects by points in descending order, then print their names.