Using a Comparator
The following is an example that demonstrates the power of a custom comparator. II implements the compare() method so that i operates in reverse of normal. Thus, it causes a tree set to be stored in reverse order. As the following output shows, the tree is now stored in reverse order:
Look closely at the MyCo~p class, which implements Comparator and overrides comparee ). (As explained earlier, overriding equals( ) is neither necessary nor common.) Inside comparee ), the String method compareTo() compares the two strings. However, bStr-not aStr-invokes compac To( ). This causes the outcome of the comparison to be reversed. .
For a more practical example, the following program is an updated version of the TreeMap program from the previous section that stores account balances. In the previous version, the accounts were sorted by name, but the sorting began with the first name. The following program sorts the accounts by last name. To do so, it uses a .,comparator that compares the last name of each account. This results in the map being sorted by last name.
Here is the output: notice-that the accounts are now sorted by last name:
Jane Daker: 1378.0
John Doe: 3434.34
Todd Hall: 9~'22
Ralph Smith: ~)9.08
Tom Smith: 123.22
John Doe's new balance: 4434.34
The comparator class TComp compares two strings that hold first and last names . . It does so by first comparing last names. To do this, it' finds the index of the last space in each string and then compares the substrings of each element that begin at that point. In cases where last names arc equivalent, the first names are then compared. This yields a tree map that is sorted by last name; and within last name by first name . You can see this because Ralph Smith comes before Tom Smith in the output.