Comparator Methods and Examples

 In Java, Comparator interface is used to compare objects in order to sort them. Prior to Java 8, Comparator interface supported only two methods - comparator() and equals. However, in Java 8, many new key methods were introduced to the Comparator interface to make sorting easier.

Some of the key methods introduced in Comparator interface are:

  • int compare(t1, t2): It compares two objects and returns an integer that indicates their relative order.
  • Comparator comparing(KeyExtractor): It accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key.
  • Comparator thenComparator(KeyExtractor): It returns a lexicographic-order comparator with another comparator.
  • Comparator naturalOrder(): It returns a comparator that compares Comparable objects in a natural order.
  • Comparator reversed(): It returns a comparator that imposes the reverse ordering of this comparator.
  • Comparator reverseOrder(): It returns a comparator that imposes the reverse of the natural ordering.
  • Comparator nullFirst(Comparator): It returns a null-friendly comparator that considers null to be less than non-null.
  • Comparator nullLast(Comparator): It returns a null-friendly comparator that considers null to be greater than non-null.

Here are some examples that demonstrate how these methods work: Example 1: Sorting an array with nulls first and in natural order.

javascript
String[] arr = {"gfg", null, "ide", null}; Arrays.sort(arr, Comparator.nullsFirst(Comparator.naturalOrder())); System.out.println(Arrays.toString(arr)); Output: [null, null, gfg, ide]

Example 2: Sorting an array in reverse order.

vbnet
String[] arr = {"gfg", "course", "ide"}; Arrays.sort(arr, Comparator.reverseOrder()); System.out.println(Arrays.toString(arr)); Output: [ide, gfg, course]

Example 3: Sorting an array first by name and then by roll number.

csharp
class Student { String name; int rollNo; Student(String n, int r) { name = n; rollNo = r; } String getName() { return name; } int getRoll() { return rollNo; } public String toString() { return "(" + name + ", " + rollNo + ")"; } } Student[] arr = {new Student("abc", 120), new Student("xyz", 110), new Student("abc", 101)}; Arrays.sort(arr, Comparator.comparing(Student::getName).thenComparing(Student::getRoll)); System.out.println(Arrays.toString(arr)); Output: [(abc, 101), (abc, 120), (xyz, 110)]




Previous Post Next Post