Programming Tutorials

compare() example in Java

By: Emiley J in Java Tutorials on 2007-09-14  

The following is an example that demonstrates the power of a custom comparator. It implements the compare() method so that it operates in reverse of normal. Thus, it causes a tree set to be stored in reverse order.

import java.util.*;

// A reverse comparator for strings.
class MyComp implements Comparator {
    public int compare(String a, String b) {
        // reverse the comparison
        return b.compareTo(a);

class CompDemo {
    public static void main(String args[]) {
        // Create a tree set with custom comparator
        TreeSet ts = new TreeSet(new MyComp());
        // Add elements to the tree set
        // Get an iterator
        Iterator i = ts.iterator();
        // Display elements
        while(i.hasNext()) {
            String element =;
            System.out.print(element + " ");

As the following output shows, the tree is now stored in reverse order:


Look closely at the MyComp class, which implements Comparatorand overrides compare(). (As explained earlier, overriding equals() is neither necessary nor common.) Inside compare(), the String method compareTo() compares the two strings. However, bStr-not aStr-invokes compareTo(). 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.

import java.util.*;

// Compare last whole words in two strings.
class TComp implements Comparator {
    public int compare(String aStr, String bStr) {
        int i, j, k;
        // find index of beginning of last name
        i = aStr.lastIndexOf(' ');
        j = bStr.lastIndexOf(' ');
        k = aStr.substring(i).compareTo(bStr.substring(j));
        if (k == 0) // last names match, check entire name
            return aStr.compareTo(bStr);
            return k;

class TreeMapDemo2 {
    public static void main(String args[]) {
        // Create a tree map
        TreeMap tm = new TreeMap<>(new TComp());
        // Put elements to the map
        tm.put("John Doe", 3434.34);
        tm.put("Tom Smith", 123.22);
        tm.put("Jane Baker", 1378.00);
        tm.put("Todd Hall", 99.22);
        tm.put("Ralph Smith", -19.08);
        // Get a set of the entries
        Set> set = tm.entrySet();
        // Get an iterator
        Iterator> itr = set.iterator();
        // Display elements
        while (itr.hasNext()) {
            Map.Entry me =;
            System.out.print(me.getKey() + ": ");
        // Deposit 1000 into John Doe's account
        double balance = tm.get("John Doe");
        tm.put("John Doe", balance + 1000);
        System.out.println("John Doe's new balance: " + tm.get("John Doe"));

Here is the output; notice that the accounts are now sorted by last name:

Jane Baker: 1378.0
John Doe: 3434.34
Todd Hall: 99.22
Ralph Smith: -19.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 are 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.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)