TreeMap with Comparator
Home ] Up ] Vector/Enumeration Example ] ArrayList/Iterator Example ] LinkedList Example ] Stack Example ] Comparable Example ] Comparator Example ] HashSet Example ] TreeSet Example ] TreeSet with Comparator ] HashMap Example ] TreeMap Example ] [ TreeMap with Comparator ]

 

 

Here's the ReversedTreeMap example, converted to using generics:

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<String, String> map = 
          new TreeMap<String, String>( 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<Map.Entry<String, String>> iter = map.entrySet().iterator(); iter.hasNext(); )
    {
      Map.Entry<String, String> entry = iter.next(); // Note NO required cast
      String key = entry.getKey(); // Note NO required cast
      String value = entry.getValue(); // Note NO required cast
      System.out.println(key + ":" + value);
    }
  }
}

class ReverseOrderKeyComparator implements Comparator<String>
{
  public int compare(String s1, String s2)
  {
    return -(s1.compareTo(s2));
    // Reverse order by reversing comparison
  }
}

which outputs the following (same as original):

Vanessa:555-7890
Sylvia:555-3456
Mary:555-1234
Joe:555-9012
Frank:555-0987

 

This page was last modified on 27 November, 2007