Comparator

Java Comparator interface 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. 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.

int compare(T object1, T object2)

The compare method returns zero if object1 is less than object2, zero if object1 and object2 are equal and negative number if object1 is greater than object2.

boolean equals(Object obj)

Returns true if the object obj is equal to this comparator object.

The class implementing the Comparator interface must define 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 super class of all the Java classes).

The Comparator interface 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 the objects of a Product class using price in descending order.

Once the custom Comparator is created for your custom class, you can use pass that to Collections.sort or Arrays.sort method to sort the objects using custom Comparator.

Here are some of the Java Comparator examples which show how to use the Java Comparator interface to sort the objects.

Java Comparator Examples

Join 1000+ fellow learners! Enter your email address below: