Using Comparator.comparing()
for Sorting
In Java 8 and later, the Comparator.comparing()
method provides a more concise and readable way to create comparators for sorting, especially when working with custom objects. This method allows you to define the sorting logic in a functional style using lambda expressions or method references.
The Comparator.comparing()
method is part of the java.util.Comparator interface and can be used to create a comparator based on a specific property of an object.
1. Basic Example: Sorting by a Single Property
For a simple use case, we can use Comparator.comparing()
to sort a list of objects based on a single property.
Example (Sorting by Name):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " (" + age + ")";
}
}
public class ComparatorComparingExample {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Alice", 25));
list.add(new Person("Bob", 30));
list.add(new Person("Charlie", 20));
System.out.println("Before sorting: " + list);
// Sorting by name using Comparator.comparing()
list.sort(Comparator.comparing(person -> person.name));
System.out.println("After sorting by name: " + list);
}
}
Output:
Before sorting: [Alice (25), Bob (30), Charlie (20)]
After sorting by name: [Alice (25), Bob (30), Charlie (20)]
Explanation:
Comparator.comparing(person ->
person.name
)
creates a comparator based on thename
field of thePerson
objects.The list is then sorted using
list.sort()
with this comparator.
2. Sorting by Multiple Properties (Chaining Comparators)
we can chain multiple comparisons using thenComparing()
. This allows you to sort first by one property and then by another if the first properties are equal.
Example (Sorting by Age and Name):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ComparatorComparingMultipleExample {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Alice", 25));
list.add(new Person("Bob", 30));
list.add(new Person("Alice", 20));
list.add(new Person("Charlie", 20));
System.out.println("Before sorting: " + list);
// Sorting by name and then by age
list.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
System.out.println("After sorting by name and age: " + list);
}
}
Output:
Before sorting: [Alice (25), Bob (30), Alice (20), Charlie (20)]
After sorting by name and age: [Alice (20), Alice (25), Bob (30), Charlie (20)]
Explanation:
Comparator.comparing(Person::getName)
sorts by name.thenComparing(Person::getAge)
sorts by age when the names are the same.
In this example, Alice appears twice, so after sorting by name, we sort by age.
3. Using Method References with Comparator.comparing()
we can use method references with Comparator.comparing()
to make the code more concise and readable.
Example (Sorting by Age Using Method Reference):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ComparatorComparingMethodReference {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Alice", 25));
list.add(new Person("Bob", 30));
list.add(new Person("Charlie", 20));
System.out.println("Before sorting: " + list);
// Sorting by age using method reference
list.sort(Comparator.comparing(Person::getAge));
System.out.println("After sorting by age: " + list);
}
}
Output:
Before sorting: [Alice (25), Bob (30), Charlie (20)]
After sorting by age: [Charlie (20), Alice (25), Bob (30)]
Explanation:
Comparator.comparing(Person::getAge)
sorts by theage
property of thePerson
objects using a method reference togetAge()
.
4. Reversing the Order Using Comparator.reverseOrder()
we can also reverse the order of sorting by using Comparator.reverseOrder()
in combination with comparing()
.
Example (Sorting by Age in Descending Order):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ComparatorReverseOrderExample {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Alice", 25));
list.add(new Person("Bob", 30));
list.add(new Person("Charlie", 20));
System.out.println("Before sorting: " + list);
// Sorting by age in descending order
list.sort(Comparator.comparing(Person::getAge).reversed());
System.out.println("After sorting by age (descending): " + list);
}
}
Output:
Before sorting: [Alice (25), Bob (30), Charlie (20)]
After sorting by age (descending): [Bob (30), Alice (25), Charlie (20)]
Explanation:
Comparator.comparing(Person::getAge).reversed()
creates a comparator that sorts by age in descending order.
Summary
Comparator.comparing()
: Creates a comparator based on a property of an object.thenComparing()
: Used to chain multiple comparators (i.e., to sort by multiple properties).Method References: Makes the code more concise when using
Comparator.comparing()
.Reversing the Order: Use
.reversed()
to sort in descending order.
The Comparator.comparing()
method provides a clear and functional way to define custom sorting logic, making it highly effective for sorting lists of objects based on one or more attributes.