Sorting Lists with List.sort()
You'll learn why List.sort() is now the preferred way to sort mutable lists in place.
The Modern Approach to Sorting Lists
In earlier Java versions, you'd use Collections.sort(list) to sort a list. Starting with Java 8, the List interface itself gained a sort() method, making this operation more intuitive and object-oriented.
Instead of passing your list to a static utility method, you now call the method directly on the list:
List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));
// Old way (still works, but less idiomatic)
Collections.sort(names);
// New way (preferred)
names.sort(null); // null means use natural ordering
Why List.sort() Is Better
Object-oriented design: It feels more natural to ask a list to sort itself rather than hand it to an external utility. The list is responsible for its own behavior.
Flexibility: The method signature is void sort(Comparator<? super E> c), taking a Comparator or null for natural ordering:
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 2, 8, 1));
numbers.sort(null); // natural order: [1, 2, 5, 8]
numbers.sort(Comparator.reverseOrder()); // [8, 5, 2, 1]
Clean chaining: Works smoothly with modern Comparator factory methods:
List<String> words = new ArrayList<>(Arrays.asList("apple", "pie", "a"));
words.sort(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
Both methods ultimately use the same sorting algorithm (typically TimSort), so performance is identical. The difference is purely stylistic and architectural.
Key Takeaway: Use List.sort(comparator) as the modern, idiomatic way to sort mutable lists in place—it's cleaner and more object-oriented than Collections.sort().