1. It’s present in java.util.package
  2. we can use comparator interface to define our own sorting

This Comparator interface defines the following 2 methods.

  1. public int compare(Object obj1, Object obj2)
    returns –ve number if obj1 has to come before obj2
    returns +ve nuber if obj1 has to come after obj2
    returns 0 if obj1 and obj2 are equal.
  2. public boolean equals(Object obj)
    When ever we are implementing comparator interface compulsory we should provide implementation for compare method. Implementing equals method is optional because it is already available from object class through inheritance.

Example:insert integer objects into the Treeset where the sorting order is descending order.

import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetComparatorDemo {
     public static void main(String[] args) {
		TreeSet t = new TreeSet(new MyComparator());
		t.add(10);
		t.add(5);
		t.add(15);
		t.add(20);
		t.add(0);
		System.out.println(t);

	}
}
class MyComparator implements Comparator {
	public int compare(Object obj1, Object obj2) {
		Integer I1 = (Integer) obj1;
		Integer I2 = (Integer) obj2;
		if (I1 < I2)
			return +1;
		else if (I1 > I2)
			return -1;
		else
			return 0;
	}
}
/*
Output:
[20, 15, 10, 5, 0]
*/

Note:If we are not passing comparator object JVM will always call compareTo() method which is meant for default natural sorting order.

Case1: If we implement compare method as follows the outputs are


public int compare(Object obj1, Object obj2){
Integer I1 = (Integer)obj1;
Integer I2 = (Integer)obj2;
return I1.compareTo(I2);// [0,5,10,15,20]
//return I2.compareTo(I1); // [20,15,10,5,0]
//return -I1.compareTo(I2); // [20,15,10,5,0]
//return -I2.compareTo(I1); // [0,5,10,15,20]
//return I2-I1;//[20,15,10,5,0]
//return I1-I2; // [0,5,10,15,20]
}

Case2: If we implement compare method as follows the outputs are


public int compare(Object obj1, Object obj2){
return -1; // [0,20,15,5,10] (reverse of Insertion order)
//return 1; // [10,5,15,20,0] (Insertion Order)
//return 0; // [10] (All the remaining elements considered as duplicate objects)
}

Example :insert String Objects to the TreeSet Where the Sorting order is reverse of Alphabetical order.

package com.java2learn.collections;
import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetComparatorStringDemo {

	public static void main(String[] args) {
		TreeSet t = new TreeSet(new MyComparatorString());
		t.add("Davidson");
		t.add("Beck");
		t.add("Bloch");
		t.add("Fleury");
		t.add("Mcclanahan");
		t.add("Johnson");
		t.add("Gosling");
		t.add("Gavin");
		//
		System.out.println(t);
	}
}

class MyComparatorString implements Comparator {
	public int compare(Object obj1, Object obj2) {
		String s1 = (String) obj1;
		String s2 = (String) obj2;
		return s2.compareTo(s1);
	}
}
/*Output
[Mcclanahan, Johnson, Gosling, Gavin, Fleury, Davidson, Bloch, Beck]
*/