Google News
logo
Java TreeMap
TreeMap
1. The underlying data Structure is Red-Black tree.
2. Insertion order is not preserved it is based some sorting order.
3. Hetrogeneous data is not allowed.
4. Duplicate objects are not allowed
5. Null insertion is possible only once.
Constructors of Java TreeMap class

TreeMapset=new TreeMap()
It is used to construct an empty tree set that will be sorted in an ascending order according to the natural order of the tree set.
TreeMap set=new TreeMap(Collection c)
It is used to build a new tree set that contains the elements of the collection c.
TreeMap set=new TreeMap(Comparator comp)
It is used to construct an empty tree set that will be sorted according to given comparator.
TreeMap set=new TreeMap(SortedSet ss)
It is used to build a TreeMapthat contains the elements of the given SortedSet.
TreeMap program
import java.util.TreeMap; 
import java.util.Set; 
import java.util.Iterator; 
import java.util.Map; 

public class Details { 

public static void main(String args[]) { 

/* This is how to declare TreeMap */ 
TreeMap tmap = 
new TreeMap(); 

/*Adding elements to TreeMap*/ 
tmap.put(1, "Data1"); 
tmap.put(23, "Data2"); 
tmap.put(70, "Data3"); 
tmap.put(4, "Data4"); 
tmap.put(2, "Data5"); 

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

} 
}
Output :
key is: 1 & Value is: Data1
key is: 2 & Value is: Data5
key is: 4 & Value is: Data4
key is: 23 & Value is: Data2
key is: 70 & Value is: Data3