Java -TreeMap class

  • TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • TreeMap contains only unique elements.
  • TreeMap cannot have null key but can have multiple null values.
  • TreeMap is same as HashMap instead maintains ascending order.
  • TreeMap is unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.

TreeMap Example

  1. import java.util.*;
  2. class TreeMapDemo
    {
  3.  public static void main(String args[]){
  4.   TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
  5.   tm.put(100,“A”);
  6.   tm.put(102,“B”);
  7.   tm.put(101,“C”);
  8.   tm.put(103,“D”);
  9.   for(Map.Entry hm:tm.entrySet()){
  10.    System.out.println(hm.getKey()+” “+hm.getValue());
  11.   }
  12.  }
  13. }
    Output:
           100 A
           101 C
           102 B
           103 D

Another TreeMap Example

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

public class TreeMapDemo1
 {

   public static void main(String args[]) {

      /* This is how to declare TreeMap */
      TreeMap<Integer, String> tmp = 
             new TreeMap<Integer, String>();

      /*Adding elements to TreeMap*/
      tmp.put(1, "A");
      tmp.put(2, "B");
      tmp.put(5, "C");
      tmp.put(3, "D");
      tmp.put(4, "E");

      /* Display content using Iterator*/
      Set set = tmp.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry m = (Map.Entry)iterator.next();
         System.out.print("key is: "+ m.getKey() + " & Value is: ");
         System.out.println(m.getValue());
      }

   }
}

Output:

key is: 1 & Value is: A
key is: 2 & Value is: B
key is: 3 & Value is: D
key is: 4 & Value is: E
key is: 5 & Value is: C
 

Leave a comment