How to Use Collections.sort in Java: Simple Guide
Use
Collections.sort(List<T> list) to sort a list in Java in natural order. For custom sorting, use Collections.sort(List<T> list, Comparator<? super T> c) with a comparator.Syntax
The Collections.sort method has two main forms:
Collections.sort(List<T> list): Sorts the list elements in their natural order (like numbers ascending or strings alphabetically).Collections.sort(List<T> list, Comparator<? super T> c): Sorts the list using a custom rule defined by the comparator.
Here, List<T> is the list you want to sort, and Comparator defines how to compare two elements.
java
Collections.sort(list); Collections.sort(list, comparator);
Example
This example shows sorting a list of strings alphabetically and then sorting a list of integers in reverse order using a comparator.
java
import java.util.*; public class SortExample { public static void main(String[] args) { List<String> fruits = new ArrayList<>(Arrays.asList("Banana", "Apple", "Orange")); Collections.sort(fruits); System.out.println("Sorted fruits: " + fruits); List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 8, 1)); Collections.sort(numbers, (a, b) -> b.compareTo(a)); // reverse order System.out.println("Numbers sorted in reverse: " + numbers); } }
Output
Sorted fruits: [Apple, Banana, Orange]
Numbers sorted in reverse: [8, 5, 3, 1]
Common Pitfalls
- Trying to sort a list of objects without natural order or without providing a comparator causes
ClassCastException. - Modifying the list while sorting can cause unexpected behavior.
- Using
Collections.sorton immutable lists throwsUnsupportedOperationException.
Always ensure the list is mutable and elements are comparable or provide a comparator.
java
import java.util.*; class Person { String name; Person(String name) { this.name = name; } } public class SortPitfall { public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person("Alice")); people.add(new Person("Bob")); // Wrong: no comparator and Person does not implement Comparable // Collections.sort(people); // This causes ClassCastException // Right: provide comparator Collections.sort(people, (p1, p2) -> p1.name.compareTo(p2.name)); for (Person p : people) { System.out.println(p.name); } } }
Output
Alice
Bob
Quick Reference
- Sort natural order:
Collections.sort(list); - Sort with custom rule:
Collections.sort(list, comparator); - List must be mutable: Use
ArrayListor similar. - Elements must be Comparable or use Comparator.
Key Takeaways
Use Collections.sort(list) to sort lists in natural order.
Provide a Comparator to sort with custom rules.
Ensure the list is mutable before sorting.
Elements must implement Comparable or use a Comparator.
Avoid modifying the list during sorting to prevent errors.