Comparator Example

Below is an example of Comparator

import java.util.Comparator;
import java.util.TreeSet;

public class MySetWithCompr {

    public static void main(String a[]){
    	MyComp obj = new MyComp();
        TreeSet<String> ts = new TreeSet<String>(obj);
        ts.add("RED");
        ts.add("ORANGE");
        ts.add("BLUE");
        ts.add("GREEN");
        ts.add("H");
        ts.add("AB");
        //Comparator cmp = ts.comparator();

        System.out.println(ts);
    }
}

//Comparator can be used for any type
//usage with String is given below
class MyComp implements Comparator<String>{

    public int compare(String str1, String str2) {
        //return str1.compareTo(str2);
    	//return str2.compareTo(str1);//sort in reverse order
    	//System.out.println("Hello from Comparator");
    	return (str1.length()-str2.length());
    }

}


You may also like to read:
Comparable Example
Difference between Comparator and Comparable