What is the Java Comparator interface?
The Java Comparator interface is used to provide a custom sorting order for a data structure; this is usually done with user-defined types. The Comparator interface is passed on to a sorting function (i.e., Collections.sort()) to temporarily alter the sorting criteria of a collection:
compare(obj1, obj2)
It is necessary to override this method when using the Comparator interface; the method should return:
- a negative integer, if
obj1is less thanobj2. - zero, if
obj1is equal toobj2. - a positive integer, if
obj1is greater thanobj2.
Code
In the following code, an ArrayList of type Person is sorted on the basis of id using a Comparator:
ComparatorShot.java
Person.java
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;public class ComparatorShot {public static void main(String[] args) {ArrayList<Person> arr = new ArrayList<>();arr.add(new Person(1, "John"));arr.add(new Person(5, "Terry"));arr.add(new Person(0, "Lukaku"));arr.add(new Person(2, "Pablo"));// Passing Comparator anonymously:Collections.sort(arr, new Comparator<Person>() {@Overridepublic int compare(Person p1, Person p2) {// Sorting by IDs:if(p1.id < p2.id)return -1;else if(p1.id > p2.id)return 1;elsereturn 0;}});// Displaying sorted array:arr.forEach(System.out::println);}}
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved