- TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
- TreeMap contains only unique elements.
- TreeMap cannot have null key but can have multiple null values.
- TreeMap is same as HashMap instead maintains ascending order.
- TreeMap is unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.
TreeMap Example
- import java.util.*;
- class TreeMapDemo
{ - public static void main(String args[]){
- TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
- tm.put(100,“A”);
- tm.put(102,“B”);
- tm.put(101,“C”);
- tm.put(103,“D”);
- for(Map.Entry hm:tm.entrySet()){
- System.out.println(hm.getKey()+” “+hm.getValue());
- }
- }
- }
Output:
100 A 101 C 102 B 103 D
Another TreeMap Example
import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
public class TreeMapDemo1
{
public static void main(String args[]) {
/* This is how to declare TreeMap */
TreeMap<Integer, String> tmp =
new TreeMap<Integer, String>();
/*Adding elements to TreeMap*/
tmp.put(1, "A");
tmp.put(2, "B");
tmp.put(5, "C");
tmp.put(3, "D");
tmp.put(4, "E");
/* Display content using Iterator*/
Set set = tmp.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry m = (Map.Entry)iterator.next();
System.out.print("key is: "+ m.getKey() + " & Value is: ");
System.out.println(m.getValue());
}
}
}
Output:
key is: 1 & Value is: A
key is: 2 & Value is: B
key is: 3 & Value is: D
key is: 4 & Value is: E
key is: 5 & Value is: C