Sorting Lists
To sort a List, pass it to the sort method of the java.util.Collections class.
Collections.sort(planets);
Collections.sort modifies the actual object you pass, without creating and returning a new List.
- This version of
sortrequires a list ofComparablesand uses their natural sort order.
For a list of non-Comparable objects, or to customize the sort, use a Comparator with Collections.sort.
public class PlanetDiameterComparator implements Comparator<Planet> {
public int compare(Planet a, Planet b) {
if (a.getDiameter() < b.getDiameter())
return -1;
else if (a.getDiameter() > b.getDiameter())
return 1;
else
return a.getName().compareTo(b.getName());
}
}
PlanetDiameterComparator comp = new PlanetDiameterComparator();
Collections.sort(planets, comp);
Java 8 introduced the ability for a List to sort itself, using a Comparator.
planets.sort(new PlanetReverseDiameterComparator());
Practice Exercise¶
The
Listinterface was first published in Java 1.2. Thesortmethod was added in version 1.8. Adding a newabstractmethod toListwould have broken the contract used by all the many existing implementing classes. However there were compelling reasons forsortand other new methods.This need to add methods to an interface without breaking existing implementors is the reason Java 8 introduced
defaultmethods. Because the Java 8Listprovides adefaultimplementation ofsort, no existing implementors had to be modified.