Java Comparator tutorial with examples will help you understand how to use the Comparator interface in an easy way. Comparator interface in Java is used to define the order of objects of the custom or user defined class.
The Java Comparator interface is contained in the java.util package, so you need to import java.util package in order to use the Comparator interface in the code. The Comparator interface contains two methods, compare
and equals
.
1 |
int compare(T object1, T object2) |
The compare
method returns a negative number if object1 is less than object2, zero if object1 and object2 are equal, and a positive number if object1 is greater than the object2.
1 |
boolean equals(Object obj) |
The equals
method returns true if the specified object is equal to this comparator object.
The class implementing the Comparator interface must define the compare
method. You may skip implementing the equals
method if you want to use the default equals
method defined in the Object class (which is a superclass of all the Java classes).
The Comparator interface in Java is used to sort or order the object of a custom class using various criteria. For example, if you have a Product class and you want to sort its objects by the price in descending order or by product name in ascending order.
Once the custom Comparator is created for your class, you can use pass that to the sort
method of the Collections class or Array class to sort the objects using the custom Comparator.
As compared to the Comparable interface which allows only one implementation to sort and compare the objects, the Comparator interface allows us to sort the class objects in multiple ways. For example, consider below given Emp class representing employees.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Emp{ private String name; private double salary; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
It is not possible to sort the objects of the Emp class by salary in ascending order as well as by age in descending order if the Emp class implements the Comparable interface. It is because the class can have only one implementation of the comareTo
method. However, by defining custom Comparator classes you can do that as given in the below example code which has Emp objects stored in an ArrayList.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class Emp{ private String name; private int salary; private int age; public Emp(String name, int salary, int age){ this.name = name; this.salary = salary; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "(" + getName() + ", " + getAge() + ", " + getSalary() + ")"; } } /* * To create custom comparator class, implement Comparator interface * and implement compareTo method. */ /* * 1. this comparator will sort employee objects according to * their age. */ class EmpAgeComparator implements Comparator<Emp>{ public int compare(Emp e1, Emp e2) { return e1.getAge() - e2.getAge(); } } /* * 2. this comparator will sort employee objects according to * their salary. */ class EmpSalaryComparator implements Comparator<Emp>{ public int compare(Emp e1, Emp e2) { return e1.getSalary() - e2.getSalary(); } } public class ComparatorExample { public static void main(String[] args) { //create some Emp objects ArrayList<Emp> listEmp = new ArrayList<Emp>(); listEmp.add( new Emp("John", 98000, 40) ); listEmp.add( new Emp("Mark", 67000, 42) ); listEmp.add( new Emp("Oliver", 120000, 28) ); //list without sorting System.out.println("Emp list without sorting"); System.out.println( listEmp ); //sort the list using age comparator Collections.sort( listEmp, new EmpAgeComparator() ); System.out.println("Emp list after sorting by age"); System.out.println(listEmp); //sort the list using salary comparator Collections.sort( listEmp, new EmpSalaryComparator() ); System.out.println("Emp list after sorting by salary"); System.out.println(listEmp); } } |
Output
1 2 3 4 5 6 |
Emp list without sorting [(John, 40, 98000), (Mark, 42, 67000), (Oliver, 28, 120000)] Emp list after sorting by age [(Oliver, 28, 120000), (John, 40, 98000), (Mark, 42, 67000)] Emp list after sorting by salary [(Mark, 42, 67000), (John, 40, 98000), (Oliver, 28, 120000)] |
The above given code has defined two custom Comparator classes for the Emp class. One comparator class sorts the employee objects using the age in ascending order and another class sorts the employee objects by the salary in ascending order. You can have as many Comparator implementations as you want for the given class.
As you can see from the output, the Emp objects are sorted by age and salary in the ascending order. If you want to sort the employee objects by age in descending order, you need to change the comparator implementation as given below.
1 2 3 4 5 6 7 |
class EmpAgeComparator implements Comparator<Emp>{ public int compare(Emp e1, Emp e2) { //return e1.getAge() - e2.getAge(); return e2.getAge() - e1.getAge(); } } |
Output
1 2 3 4 5 6 |
Emp list without sorting [(John, 40, 98000), (Mark, 42, 67000), (Oliver, 28, 120000)] Emp list after sorting by age [(Mark, 42, 67000), (John, 40, 98000), (Oliver, 28, 120000)] Emp list after sorting by salary [(Mark, 42, 67000), (John, 40, 98000), (Oliver, 28, 120000)] |
As you can see from the output, the Emp objects are now sorted by the age in the descending order.
Java Comparator Examples
- Search object in ArrayList using Comparator
- How to convert HashMap to TreeMap using Comparator
- How to sort HashMap by keys using Comparator
- How to sort HashMap by values using Comparator
- How to sort ArrayList using Comparator
- How to sort objects using Comparator in ascending and descending order
- How to sort String[] array using Comparator
- Sort elements of LinkedList using Comparator interface
- How to sort LinkedHashMap by keys using Comparator
- How to sort LinkedHashMap by values using Comparator
- How to sort HashSet using Comparator
- How to sort TreeSet using Comparator
- How to sort LinkedHashSet using Comparator
- Sort Java Vector using Comparator
- Find min max elements from Vector using the Comparator
References:
Java Comparator interface Javadoc
Please let me know if you liked the Java Comparator tutorial with examples in the comments section below.