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:
obj1
is less than obj2
.obj1
is equal to obj2
.obj1
is greater than obj2
.In the following code, an ArrayList of type Person
is sorted on the basis of id
using a Comparator:
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