Collection Java Book

The comparator defines what is the order.
Comparator is a generic interface that has the declaration of:
interface Comparator
T specifies the type of objects being compared.
The Comparator interface defines two methods: compare( ) and equals( ).
The compare( ) method compares two elements for order:
int compare(T obj1, T obj2)
obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal.
It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.
The method throws a ClassCastException if the types of the objects are not compatible for comparison. By overriding compare( ), you can alter the way that objects are ordered.
The equals( ) method tests whether an object equals the invoking comparator:
boolean equals(Object obj)
obj is the object to be tested for equality.
The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.
Overriding equals( ) is unnecessary.
The following code implements Comparator.

/**
*Output:
F E D C B A
*/
import java.util.Comparator;
import java.util.TreeSet;
class MyComparator implements Comparator {
public int compare(String a, String b) {
String aStr, bStr;
aStr = a;
bStr = b;
return bStr.compareTo(aStr);
}
// No need to override equals.
}
public class MainClass {
public static void main(String args[]) {
TreeSet ts = new TreeSet(new MyComparator());
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
for (String element : ts)
System.out.print(element + " ");
System.out.println();
}
}

The following code shows how to define your own class and use it in a TreeSet. The TreeSet requires its element to be a Comparator.

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
// Compare last whole words in two strings.
class LastNameComparator implements Comparator {
public int compare(String a, String b) {
int k;
// Find index of beginning of last name.
k = a.substring(a.lastIndexOf(' ')).compareTo(b.substring(b.lastIndexOf(' ')));
if (k == 0){
return a.compareTo(b);// last names match, check entire name
}
else{
return k;
}
}
}
public class Main {
public static void main(String args[]) {
TreeMap tm = new TreeMap(new LastNameComparator());
// Put elements to the map.
tm.put("J E", new Double(3434.34));
tm.put("T D", new Double(123.22));
tm.put("J C", new Double(1378.00));
tm.put("T B", new Double(99.22));
tm.put("R A", new Double(-19.08));
// Get a set of the entries.
Set> set = tm.entrySet();
// Display the elements.
for (Map.Entry me : set) {
System.out.println(me.getKey());
}
}
}