TreeMap in Java

  • The TreeMap class extends AbstractMap and implements SortedMap interface.
  • The TreeMap uses tree Structure for internal storage.
  • The TreeMap provides an efficient means of storing key or value pairs in sorted order, and allows rapid retrieval.
  • The TreeMap value can get by Iterator interface.
  • The TreeMap is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally using Collections.synchronizedMap( mapName ).
The following table demonstrates the constructors of TreeMap and corresponding methods.

Constructor
Meaning
TreeMap()
Constructs a new empty map object.
TreeMap (Map m)
Constructs a new map with the given map.
TreeMap (Comparator cmp)
Constructs a new map, sorted according to the given comparator.
TreeMap (SortedMap sp)
Constructs a new map, sorted according to the given sorted map.

The following program shows a simple use of TreeMap.

Example:

/**
From SimpleTreeMap.java
*/

import java.util.TreeMap;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleTreeMap
{
 public static void main(String args[])
  {
      TreeMap<String,Float> tmap = new TreeMap<String,Float>();
      tmap.put("Apple", new Float(88.91));
      tmap.put("Grape", new Float(78.45));
      tmap.put("Banana", new Float(92.61));
      tmap.put("Mango", new Float(95.11));
      tmap.put("Orange", new Float(82.54));
      tmap.put("Pinapple", new Float(73.41));
      System.out.println("The HashMap elements are"+"\n"+tmap);
  }
}

Output
The HashMap elements are
{Apple=88.91, Banana=92.61, Grape=78.45, Mango=95.11, Orange=82.54, Pinapple=73.41}


The following program shows use of TreeMap with Iterator and Map Interface.

Example:

/**
From TreeMapwithIterator.java
*/

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 *
 * @author JavaHotSpot
 */

public class TreeMapwithIterator
{
    public static void main(String args[])
  {
      TreeMap<String,Float> tmap = new TreeMap<String,Float>();
      tmap.put("Apple", new Float(88.91));
      tmap.put("Grape", new Float(78.45));
      tmap.put("Banana", new Float(92.61));
      tmap.put("Mango", new Float(95.11));
      tmap.put("Orange", new Float(82.54));
      tmap.put("Pinapple", new Float(73.41));
      System.out.println("The HashMap elements are");
      Set set = tmap.entrySet();
      Iterator it = set.iterator();
      while(it.hasNext())
      {
          Map.Entry mapent = (Map.Entry)it.next();
          System.out.println(mapent.getKey()+"="+mapent.getValue());
      }
  }
}

Output
The HashMap elements are
Apple=88.91
Banana=92.61
Grape=78.45
Mango=95.11
Orange=82.54