Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java TreeMap

  • • It is another implementation class of Map interface.
  • • It contains values based on the key.
  • • It contains only unique elements.
  • • It cannot have null key but can have multiple null values.
  • • It performs sorting operation, here keys will sort, that means all keys will represent in the form of sorting order.
Let's see a program:
TreeMapDemo.java:
import java.util.*;
class TreeMapDemo
{
public static void main(String args[])
{
TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
hm.put(100,"Tapuuu");
hm.put(102,"Silan");
hm.put(101,"Sushh");
hm.put(103,"Manu");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());

}
}
}

Output

100 Tapuuu
101 Sushh
102 Silan
103 Manu

HashMap vs. TreeMap:


HashMap is can contain one null key. TreeMap can not contain any null key.
HashMap maintains no order. TreeMap maintains ascending order.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext