All for Joomla All for Webmasters

Java TreeMap class

  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • It is same as HashMap instead maintains ascending order.

Example of TreeMap class:

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

What is difference between HashMap and TreeMap?

1) HashMap is can contain one null key. TreeMap can not contain any null key.
2) HashMap maintains no order. TreeMap maintains ascending order.
submit to reddit

Leave a Reply