What is a Comparator in Java? Use it with code
In Java, a Comparator
is an interface that defines a method for comparing two objects of a specific type. It is used to provide custom ordering for collections of objects, such as sorting a list or an array. The Comparator
interface is part of the java.util
package and has a single method, compare(T o1, T o2)
, which compares its two arguments for order.
Comparator
can be used to define multiple sorting orders for the same class.List
, Set
, or arrays.Comparator
interface either by creating a separate class or using a lambda expression (Java 8 and later).Here’s an example of how to use a Comparator
to sort a list of Person
objects by their age:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
// Define a Person class
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public class ComparatorExample {
public static void main(String[] args) {
// Create a list of Person objects
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// Sort the list using a Comparator
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.age, p2.age); // Compare by age
}
});
// Print the sorted list
System.out.println("Sorted by age:");
for (Person person : people) {
System.out.println(person);
}
// Alternatively, using a lambda expression (Java 8 and later)
Collections.sort(people, (p1, p2) -> p1.name.compareTo(p2.name)); // Sort by name
// Print the sorted list by name
System.out.println("\nSorted by name:");
for (Person person : people) {
System.out.println(person);
}
}
}
name
and age
attributes.Person
objects.Collections.sort()
with a custom Comparator
to sort the list by age.Sorted by age:
Bob (25)
Alice (30)
Charlie (35)
Sorted by name:
Alice (30)
Bob (25)
Charlie (35)
This example illustrates how to use a Comparator
to sort objects in different ways based on different attributes.