The sort()
method in Java’s ArrayList
class is a highly practical feature for ordering elements in a list based on natural order or custom rules. Introduced in Java 8, this method leverages functional programming by accepting a comparator, making sorting operations on dynamic lists much simpler, more flexible, and more expressive.
What Is the sort() Method in ArrayList?
- The
sort()
method sorts the elements of theArrayList
in place, modifying the original list. - It accepts a Comparator as an argument, defining the order for sorting.
- If
null
is passed as the comparator, the list is sorted in natural order (i.e., ascending for numbers, alphabetically for strings).
Syntax
public void sort(Comparator<? super E> c)
Where:
c
is a comparator (can be a lambda, method reference, ornull
for natural order).E
is the type of the elements in the list.
Parameters
Parameter | Description |
---|---|
c | Comparator for custom sorting; null to sort by natural order of element type. |
Return Value
void
– This method does not return a value. The list is sorted in place.
Exceptions
ClassCastException
: Thrown if the list elements are not mutually comparable.UnsupportedOperationException
: Thrown if the list cannot be modified (rare; e.g., immutable lists).IllegalArgumentException
: If the comparator is inconsistent with equals.
How Does sort() Work Internally?
- The
sort()
method uses a modified merge sort (stable, adaptive, iterative). - Either the provided comparator or the elements’ natural ordering (via
compareTo()
) is used for comparison. - The method is efficient and stable for lists of any size.
Examples of the sort() Method
1. Sort Strings in Alphabetical Order
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cities = new ArrayList<>(); cities.add("Delhi"); cities.add("Mumbai"); cities.add("Chennai"); cities.sort(null); // Sorts alphabetically System.out.println(cities); // Output: [Chennai, Delhi, Mumbai] } }
2. Sort Integers in Ascending and Descending Order
import java.util.ArrayList; import java.util.Comparator; public class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(2); numbers.add(35); // Sort ascending (natural order) numbers.sort(null); System.out.println(numbers); // Output: [2, 10, 35] // Sort descending using Comparator numbers.sort(Comparator.reverseOrder()); System.out.println(numbers); // Output: [35, 10, 2] } }
3. Sort Custom Objects Using Comparator
import java.util.ArrayList; import java.util.Comparator; class Student { String name; int age; Student(String name, int age) { this.name = name; this.age = age; } public String toString() { return name + " (" + age + ")"; } } public class Demo { public static void main(String[] args) { ArrayList<Student> students = new ArrayList<>(); students.add(new Student("Alex", 23)); students.add(new Student("Brian", 20)); // Sort by age (ascending) students.sort(Comparator.comparingInt(s -> s.age)); System.out.println(students); // Output: [Brian (20), Alex (23)] } }
4. Sort Strings by Length Using Lambda
import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<String> animals = new ArrayList<>(); animals.add("Elephant"); animals.add("Dog"); animals.add("Cat"); // Sort by string length (ascending) animals.sort((a, b) -> Integer.compare(a.length(), b.length())); System.out.println(animals); // Output: [Dog, Cat, Elephant] } }
Important Notes
- In-place sorting: The original list is reordered; sorting does not create a new list.
- Null values: If present,
sort()
may throwNullPointerException
. - Natural order: Use
null
as the comparator to sort with the natural order of the list’s elements. - Custom rules: You can use lambdas or method references to provide complex sorting logic.
- Stability: Sorting is stable—equal elements retain their original position.
Summary
Aspect | Details |
---|---|
Method Purpose | Sorts elements in an ArrayList in place |
Syntax | list.sort(Comparator<? super E> c) |
Parameters | Comparator for custom order (or null for natural) |
Return Value | None (void) |
Exceptions | ClassCastException , NullPointerException , UnsupportedOperationException |
Typical Use Cases | Alphabetical sorting, numeric sorting, custom order |
Typical Use Cases
- Sorting data for display (e.g., names, numbers, custom objects).
- Batch processing where results need to be in order for further tasks.
- Data normalization and presentation, such as reports, charts, or UIs.
- Custom ranking (leaderboards, top-N lists, etc.).