TreeMap with Comparator
Home ] Up ] Map Interface ] HashMap Class ] SortedMap Interface ] TreeMap Class ] [ TreeMap with Comparator ]

 

 

To change the order in which the TreeMap orders its elements, you can use a Comparator object, as before:

package examples;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class ReversedTreeMapExample
{
  public static void main(String[] args)
  {
    TreeMap map = new TreeMap( new ReverseOrderKeyComparator() );
    map.put("Mary", "555-1234");
    map.put("Frank", "555-5678");
    map.put("Joe", "555-9012");
    map.put("Sylvia", "555-3456");
    map.put("Vanessa", "555-7890");
    map.put("Frank", "555-0987");   // Duplicate
    for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); )
    {
      Map.Entry entry = (Map.Entry) iter.next(); // Note required cast
      String key = (String) entry.getKey(); // Note required cast
      String value = (String) entry.getValue(); // Note required cast
      System.out.println(key + ":" + value);
    }
  }
}
class ReverseOrderKeyComparator implements Comparator
{
  public int compare(Object o1, Object o2)
  {
    String s1 = (String) o1;
    String s2 = (String) o2;
    return -(s1.compareTo(s2));
    // Reverse order by reversing comparison
  }
}

which outputs the following:

Vanessa:555-7890
Sylvia:555-3456
Mary:555-1234
Joe:555-9012
Frank:555-0987
showing the expected reverse order by key.

 

This page was last modified on 02 October, 2007