Java TreeMap class

  • The TreeMap class implements the Map interface by using a tree.
  • A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.
  • It contains only unique elements
  • It is same as HashMap instead maintains ascending order.
second

Example of TreeMap

import java.util.*; 

	class DemoTM{ 

	public static void main(String args[]){ 

	

	TreeMap tm=new TreeMap(); 

	

	tm.put(101,"A"); 

	tm.put(102,"C"); 

	tm.put(103,"B"); 

	tm.put(101,"D"); 

	

	for(Map.Entry m:tm.entrySet()){ 

	System.out.println(m.getKey()+" "+m.getValue()); 

	} 

	} 

	} 

								

				
				
				
				
						
						
						
						

Output


101 D

102 C

103 B

What is difference between HashMap and TreeMap

SN HashMap 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.