TreeMap class

 

See Map interface  for descriptions and examples of most of TreeMap's methods (except those below).

 

TreeMap implements SortedMap, and extends AbstractMap

 

TreeMap is for everyday sorted Map usage, where the order of the keys is important.  It provides ascending keys automatically. 

i.e. This snippet prints the keys and values in ascending key order, from Ant to Elephant, despite the fact they were put into the TreeMap in a different order:

 

import java.util.*;

 

TreeMap tm = new TreeMap( );

tm.put("ElephantKey", "Elephant");

tm.put("DogKey", "Dog");

tm.put("CatKey", "Cat");

tm.put("AntKey", "Ant");

tm.put("BunnyKey", "Bunny");

System.out.println( tm );

 

TreeMap allows null values and (one) null key.

 

TreeMap tm = new TreeMap( );

tm.put("AnimalKey", "DogValue");

tm.put("AnimalKey", "CatValue");

tm.put("AnimalKey", "DogValue"); 

 

System.out.println( tm );

 

TreeMap adds a few methods to those in Map:

 

 

SortedMap  .subMap( fromObjKey, toObjKey )    method

 

■ (For TreeMap only) Returns the mappings whose keys range from fromObjKey inclusive, to toObjKey exclusive.

 

import java.util.*;

 

TreeMap tm = new TreeMap( );

tm.put("0", "");

tm.put("1","One");

tm.put("2","Two");

tm.put("3","Three");

tm.put("4","Four");

tm.put("5","Five");

                                System.out.println(tm);

 

Map sm = new TreeMap( );

sm = tm.subMap("2", "5");                   // returns all the k=v mappings from keys "2" to "4"

System.out.println(sm); 

 

 

 

SortedMap  .tailMap( fromObjKey )    method

 

■ (For TreeMap only) Returns the mappings whose keys are greater than or equal to fromKey.

 

import java.util.*;

 

// Uses the tm Map from the example above

Map tmap = new TreeMap( );

tmap = tm.tailMap("3");                        // returns all the k=v mappings where k >= "3"

System.out.println(tmap);

 

 

Object  .firstKey( )    method

 

■ (For TreeMap only) Returns the first or lowest key.

 

 

import java.util.*;

 

// Uses the tm Map example from above

System.out.println(tm.firstKey( ));                     // finds the lowest key in tm, which is "0"

 

 

Object  .lastKey( )    method

 

■ (For TreeMap only) Returns the last or highest key.

 

import java.util.*;

 

// Uses the tm Map from the examples above

System.out.println(tm.lastKey( ));                     // returns "5" the highest key

 

 

 

SortedMap  .headMap( toObjKey )    method

 

■ (For TreeMap only) Returns the mappings whose keys are less than toObjKey.

 

import java.util.*;

 

// Uses the tm Map from the examples above

Map hm = new TreeMap( );

hm = tm.headMap("3");                         // returns all the k=v mappings where k < "3"

System.out.println(hm);