Java Comparator Interface - Custom Sorting for User-Defined Classes
Master the Java Comparator interface to define custom sorting logic for user-defined classes. Essential for sorting elements in collections like TreeSet and TreeMap, Comparator allows you to establish flexible and specific criteria for ordering objects. Dive into examples and tips on using Comparator for advanced sorting in Java.
Java - How to Use Comparator
Both TreeSet
and TreeMap
store elements in a sorted order. However, the comparator defines the specific criteria for how that order is determined.
Java Comparator Interface
The Comparator
interface in Java is part of the java.util
package, and it specifies the order of objects for user-defined classes.
Methods of the Comparator Interface
The Comparator
interface defines two primary methods: compare()
and equals()
.
The compare() Method
The compare()
method compares two elements for order:
Syntax
int compare(Object obj1, Object obj2)
Output
Returns 0 if objects are equal, positive if obj1 > obj2, negative if obj1 < obj2.
By overriding compare()
, you can change the order of the objects. For instance, to sort in reverse order, you can create a comparator that inverses the comparison result.
The equals() Method
The equals()
method checks whether an object is equal to the invoking comparator:
Syntax
boolean equals(Object obj)
Output
Returns true if obj is a Comparator and uses the same ordering; otherwise, false.
Overriding equals()
is generally unnecessary, and most simple comparators will not implement it.
Using Comparator Interface to Sort Custom Objects
In this example, we will use the Comparator
interface to sort a custom object, Dog
, based on specific criteria.
Example
Syntax
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Dog implements Comparator, Comparable {
private String name;
private int age;
Dog(String n, int a) {
name = n;
age = a;
}
public int compareTo(Dog d) {
return this.name.compareTo(d.name);
}
public int compare(Dog d, Dog d1) {
return d.age - d1.age;
}
@Override
public String toString() {
return this.name + "," + this.age;
}
}
public class ComparatorDemo {
public static void main(String args[]) {
List list = new ArrayList<>();
list.add(new Dog("Buddy", 5));
list.add(new Dog("Max", 3));
list.add(new Dog("Bella", 2));
list.add(new Dog("Charlie", 4));
list.add(new Dog("Daisy", 1));
Collections.sort(list); // Sorts the array list
System.out.println("Sorted by name:");
System.out.print(list);
Collections.sort(list, new Dog());
System.out.println(" ");
System.out.println("Sorted by age:");
System.out.print(list);
}
}
Output
Sorted by name:
[Bella,2, Buddy,5, Charlie,4, Daisy,1, Max,3]
Sorted by age:
[Daisy,1, Bella,2, Max,3, Charlie,4, Buddy,5]
Note: The sorting method for the Arrays class is similar to that of the Collections class.
Using Comparator Interface for Reverse Sorting
In this example, we will utilize the Comparator
interface to sort the Dog
objects in reverse order.
Example 2
Syntax
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Dog implements Comparator, Comparable {
private String name;
private int age;
Dog(String n, int a) {
name = n;
age = a;
}
public int compare(Dog d, Dog d1) {
return d.age - d1.age;
}
@Override
public String toString() {
return this.name + "," + this.age;
}
}
public class ComparatorDemo {
public static void main(String args[]) {
List list = new ArrayList<>();
list.add(new Dog("Buddy", 5));
list.add(new Dog("Max", 3));
list.add(new Dog("Bella", 2));
list.add(new Dog("Charlie", 4));
list.add(new Dog("Daisy", 1));
Collections.sort(list, Collections.reverseOrder()); // Sorts the array list
System.out.println("Sorted by name in reverse order:");
System.out.print(list);
}
}
Output
Sorted by name in reverse order:
[Max,3, Buddy,5, Charlie,4, Bella,2, Daisy,1]
Sorting String Values in Reverse Order
In this final example, we will use the Comparator
interface to sort string values in reverse order.
Example 3
Syntax
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparatorDemo {
public static void main(String args[]) {
List list = new ArrayList<>();
list.add("Buddy");
list.add("Max");
list.add("Bella");
list.add("Charlie");
list.add("Daisy");
Collections.sort(list, Collections.reverseOrder()); // Sorts the array list
System.out.println("Sorted by name in reverse order:");
System.out.print(list);
}
}
Output
Sorted by name in reverse order:
[Max, Buddy, Charlie, Bella, Daisy]