import java.util.Comparator;
import java.util.Map;


/** 
 * Compares two Map.Entry objects for order, based first on the
 * entry's value, then its key.
 *
 * Note, this class assumes that both the key and value implement
 * Comparable interface --- maps only assume the key is Comparable.
 */
public class ValueComparator implements Comparator
{
    /**
     * Returns a negative integer, zero, or a positive integer 
     * if the first argument is less than, equal to, or greater 
     * than the second, result.
     */
    public int compare (Object lhs, Object rhs)
    {
        Map.Entry lEntry = (Map.Entry)lhs;
        Map.Entry rEntry = (Map.Entry)rhs;

        int result = 0;
        if (lEntry != null && rEntry != null)
        {
            // first compare by value
            result = ((Comparable)lEntry.getValue()).compareTo(
                      (Comparable)rEntry.getValue());

            // if equal, then compare by key
            if (result == 0)
            {
                result = ((Comparable)lEntry.getKey()).compareTo(
                          (Comparable)rEntry.getKey());
            }
        }
        return result;
    }
}
