Sorting
In short: Putting elements of a collection or an array into a specific order — Java offers ready-made methods for this like Collections.sort(list) or Arrays.sort(array).
In more detail: For custom sort orders (e.g. by a specific field of an object instead of the natural order), you pass a Comparator, either as a custom class, an anonymous class, or compactly as a lambda expression.
list.sort((a, b) -> a.getName().compareTo(b.getName()));In Depth
List<Person> people = new ArrayList<>(List.of(
new Person("Bob", 25),
new Person("Anna", 30)
));
// Natural order, if Person implements Comparable<Person>:
Collections.sort(people);
// Custom order via Comparator, e.g. by age instead of name:
people.sort(Comparator.comparingInt(Person::getAge));
// Chaining several criteria: first age, then name for ties:
people.sort(Comparator.comparingInt(Person::getAge).thenComparing(Person::getName));Java arrays are sorted via the static method Arrays.sort(array), real collections like List via Collections.sort(list) or — more concisely since Java 8 — directly via the instance method list.sort(comparator). Internally, Java uses a stable sorting algorithm for objects (a variant of Timsort, a mix of merge sort and insertion sort), which preserves the original order of equal elements — important when sorting by several criteria in sequence, as above. For primitive arrays (int[], double[], etc.), by contrast, a dual-pivot quicksort is used, which is faster but not stable — for primitive values, though, this doesn’t matter, since there are no “equal but distinguishable” elements.
Making an object “sortable” works in two ways: either the class implements Comparable<T> and thereby defines ONE natural default order (e.g. strings alphabetically), or you pass a separate Comparator at the sort call, which enables any number of alternative orders without touching the class itself.
See also: Advanced Sorting, Algorithms, Collections