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

 

 

The TreeMap class implements a SortedMap, which means that it keeps the entries in key order. 

TreeMap uses a tree to implement the SortedMap:

Object
    AbstractMap (implements Map)
        TreeMap (implements SortedMap)

Here's an example of its use:

package examples;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapExample
{
  public static void main(String[] args)
  {
    TreeMap map = new TreeMap();
    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);
    }
  }
}

which, as you can see, is minimally different from the HashMap example.

It outputs:

Frank:555-0987
Joe:555-9012
Mary:555-1234
Sylvia:555-3456
Vanessa:555-7890
which is in order by key, and also shows that the value associated with the second key value of "Frank" is the one that survives, causing the original "Frank" to be removed.

 

This page was last modified on 02 October, 2007