Tuesday, September 24, 2013

TreeMap Example in Java

TreeMap maintains ascending order and does not allows null as Key which differs in HashMap and LinkedHashMap.

About TreeMap:
  • It extends AbstractMap class and Implements NavigableMap Interface
  • It maintain ascending order
  • It does not allow null as Key
  • Contains unique elements Only

If You observe output of TreepMap example as below, Output is in Ascending order. If You try to put null as Key then NullPointerException throws as below.

Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.put(TreeMap.java:556)
at com.anuj.basic.TreeMapOperations.main(TreeMapOperations.java:23)

You may want to refer to :

Java TreeMap Example:
package com.anuj.basic;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 
 * @author Anuj
 * Maintain Accending Order
 * Does not allow null as Key
 */
public class TreeMapOperations {

 public static void main(String[] args) {
  TreeMap hashMap = new TreeMap();
  
  hashMap.put("Anuj","1");
  hashMap.put("Zvika","2");
  hashMap.put("David", "3");
  hashMap.put("David", "3");
  //hashMap.put(null,null); //Exception
  
  Set set = hashMap.entrySet();
  Iterator iterator = set.iterator();
  
  while(iterator.hasNext()){
   Map.Entry entry = (Map.Entry)iterator.next();
   System.out.println("Key:"+entry.getKey() + " Value:"+entry.getValue());
  }
 }

}

Output:
Key:Anuj Value:1
Key:David Value:3
Key:Zvika Value:2

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/