Trusted answers to developer questions

What is the Java Comparator interface?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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 obj1 is less than obj2.
  • zero, if obj1 is equal to obj2.
  • a positive integer, if obj1 is greater than obj2.
Declaring a Comparator and passing it to a sorting function.
Declaring a Comparator and passing it to a sorting function.

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>() {
@Override
public int compare(Person p1, Person p2) {
// Sorting by IDs:
if(p1.id < p2.id)
return -1;
else if(p1.id > p2.id)
return 1;
else
return 0;
}
});
// Displaying sorted array:
arr.forEach(System.out::println);
}
}

RELATED TAGS

java
comparator
interface
collection
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?