Collections.sort for List Ordering
What you'll learn: How to sort any List in Java using the Collections.sort() utility method for both natural and custom orderings.
The Core Idea
Collections.sort() is a static utility method that rearranges the elements of a List in place. Think of it like alphabetizing books on a shelf—you're organizing them according to a specific rule. By default, it uses natural ordering (the order defined by the elements' compareTo method), but you can also provide a custom Comparator to define your own sorting logic.
Natural Ordering with Collections.sort
For elements that implement Comparable (like Integer, String, LocalDate), you can sort without any extra arguments:
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9));
Collections.sort(numbers);
// numbers is now [1, 2, 5, 8, 9]
List<String> words = new ArrayList<>(Arrays.asList("zebra", "apple", "mango"));
Collections.sort(words);
// words is now ["apple", "mango", "zebra"]
The list is modified directly—there's no return value.
Custom Ordering with a Comparator
When you need different sorting logic, pass a Comparator:
List<String> words = new ArrayList<>(Arrays.asList("ant", "elephant", "bee"));
Collections.sort(words, (a, b) -> Integer.compare(a.length(), b.length()));
// words is now ["ant", "bee", "elephant"] — sorted by length
Collections.sort(numbers, (a, b) -> b - a); // reverse order
// numbers is now [9, 8, 5, 2, 1]
When to Use It
Use Collections.sort() whenever you need to order data for display, searching (binary search requires sorted data), or processing in sequence. It works on any List implementation—ArrayList, LinkedList, etc.
Key Takeaway: Collections.sort() arranges List elements in place using either natural ordering or a custom Comparator, making it the standard way to sort lists in Java.