Friday, 1 May 2015

Java TreeMap class

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.

Hierarchy of TreeMap class:



Example of TreeMap class:

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

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.


No comments:

Post a Comment

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...