Java TreeMap

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java TreeMap class

Java TreeMap class hierarchy

Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in sorted order.

The important points about Java TreeMap class are:

  • 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.

TreeMap class declaration

Let's see the declaration for java.util.TreeMap class.

  1. public class TreeMap extends AbstractMap implements NavigableMap, Cloneable, Serializable  

TreeMap class Parameters

Let's see the Parameters for java.util.TreeMap class.

  • K: It is the type of keys maintained by this map.

  • V: It is the type of mapped values.

Constructors of Java TreeMap class

Constructor

Description

TreeMap()

It is used to construct an empty tree map that will be sorted using the natural order of its key.

TreeMap(Comparator comp)

It is used to construct an empty tree-based map that will be sorted using the comparator comp.

TreeMap(Map m)

It is used to initialize a tree map with the entries from m, which will be sorted using the natural order of the keys.

TreeMap(SortedMap sm)

It is used to initialize a tree map with the entries from the SortedMap sm, which will be sorted in the same order as sm.

Methods of Java TreeMap class

Method

Description

boolean containsKey(Object key)

It is used to return true if this map contains a mapping for the specified key.

boolean containsValue(Object value)

It is used to return true if this map maps one or more keys to the specified value.

Object firstKey()

It is used to return the first (lowest) key currently in this sorted map.

Object get(Object key)

It is used to return the value to which this map maps the specified key.

Object lastKey()

It is used to return the last (highest) key currently in this sorted map.

Object remove(Object key)

It is used to remove the mapping for this key from this TreeMap if present.

void putAll(Map map)

It is used to copy all of the mappings from the specified map to this map.

Set entrySet()

It is used to return a set view of the mappings contained in this map.

int size()

It is used to return the number of key-value mappings in this map.

Collection values()

It is used to return a collection view of the values contained in this map.

Java TreeMap Example:

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

Java TreeMap Example: remove()

  1. import java.util.*;  
  2. public class TreeMapExample {  
  3.    public static void main(String args[]) {  
  4.    // Create and populate tree map  
  5.    Map<Integer, String> map = new TreeMap<Integer, String>();           
  6.    map.put(102,"Let us C");  
  7.    map.put(103"Operating System");  
  8.    map.put(101"Data Communication and Networking");  
  9.    System.out.println("Values before remove: "+ map);    
  10.    // Remove value for key 102  
  11.    map.remove(102);  
  12.    System.out.println("Values after remove: "+ map);  
  13.    }      
  14. }  

Output:

Values before remove: {101=Data Communication and Networking, 102=Let us C, 103=Operating System}
Values after remove: {101=Data Communication and Networking, 103=Operating System}

What is difference between HashMap and TreeMap?

HashMap

TreeMap

1) HashMap can contain one null key.

TreeMap can not contain any null key.

2) HashMap maintains no order.

TreeMap maintains ascending order.

Java TreeMap Example: Book

  1. import java.util.*;    
  2. class Book {    
  3. int id;    
  4. String name,author,publisher;    
  5. int quantity;    
  6. public Book(int id, String name, String author, String publisher, int quantity) {    
  7.     this.id = id;    
  8.     this.name = name;    
  9.     this.author = author;    
  10.     this.publisher = publisher;    
  11.     this.quantity = quantity;    
  12. }    
  13. }    
  14. public class MapExample {    
  15. public static void main(String[] args) {    
  16.     //Creating map of Books    
  17.     Map<Integer,Book> map=new TreeMap<Integer,Book>();    
  18.     //Creating Books    
  19.     Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);    
  20.     Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);    
  21.     Book b3=new Book(103,"Operating System","Galvin","Wiley",6);    
  22.     //Adding Books to map   
  23.     map.put(2,b2);  
  24.     map.put(1,b1);  
  25.     map.put(3,b3);  
  26.       
  27.     //Traversing map  
  28.     for(Map.Entry<Integer, Book> entry:map.entrySet()){    
  29.         int key=entry.getKey();  
  30.         Book b=entry.getValue();  
  31.         System.out.println(key+" Details:");  
  32.         System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);   
  33.     }    
  34. }    
  35. }    

Output:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6