Introduction
The `sort()` method in Java's ArrayList
allows you to sort the elements within the list based on a custom comparison logic. You provide a Comparator
object that dictates how two elements should be compared, giving you fine-grained control over the sorting process. This is particularly useful when dealing with objects or data types where the default natural ordering might not suffice.
Syntax
public void sort(Comparator<? super E> c)
Parameters
Parameter | Description |
---|---|
c |
The Comparator object that defines the order of elements in the list. If null, the list is sorted according to its natural ordering (if the elements implement the Comparable interface). |
Return Value
This method doesn't return any value; it sorts the ArrayList in place. It is a void
method.
Examples
Sorting ArrayList of Strings by Length
In this example, we sort an ArrayList of strings based on their lengths. We create a Comparator that compares two strings and returns a negative number if the first string is shorter than the second, a positive number if it's longer, and zero if they have equal length.
import java.util.*;
public class SortByLength {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList<>(
Arrays.asList("apple", "banana", "kiwi", "orange"));
strings.sort((s1, s2) -> Integer.compare(s1.length(), s2.length()));
System.out.println(strings);
}
}
[kiwi, apple, orange, banana]
Explanation: The lambda expression (s1, s2) -> Integer.compare(s1.length(), s2.length())
acts as a Comparator. It compares the lengths of two strings (s1 and s2) using Integer.compare()
. The resulting ArrayList is sorted in ascending order based on string length.
Sorting ArrayList of Integers in Descending Order
This example demonstrates sorting an ArrayList of integers in descending order. We create a Comparator that subtracts the second integer from the first, effectively reversing their natural ordering.
import java.util.*;
public class SortDescending {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(
Arrays.asList(5, 2, 8, 1, 9));
numbers.sort((a, b) -> Integer.compare(b, a)); // or (a, b) -> -Integer.compare(a, b)
System.out.println(numbers);
}
}
[9, 8, 5, 2, 1]
Explanation: The lambda expression (a, b) -> Integer.compare(b, a)
defines the Comparator. By subtracting 'a' from 'b', we reverse the natural order of integers, resulting in descending sort.
Sorting ArrayList of Custom Objects
This example showcases sorting an ArrayList of custom objects (Person
in this case) based on their age. We create a Comparator
class that compares two Person
objects and returns a value indicating their relative order.
import java.util.*;
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{ name="" + name + "", age="" + age + ""}";
}
}
public class SortByAge {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>(
Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
));
people.sort(Comparator.comparingInt(Person::age));
System.out.println(people);
}
}
[Person{ name='Bob', age=25 }, Person{ name='Alice', age=30 }, Person{ name='Charlie', age=35 }]
Explanation: The Comparator.comparingInt(Person::age)
creates a comparator that sorts the list of people based on their age. The lambda expression is replaced with this concise method call.