Java TreeMap Example

TreeMap implements the Map interface and also NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys or by a Comparator provided a the time of initialization. In terms of time complexity, this implementation provides log(n) cost for the containsKey, get, put and remove operations. It’s important to note that TreeMap is not synchronized because if the map is accessed by multiple threads, and if at least of the treads modifies the map structurally, it must be synchronized externally.

Important points about TreeMap

  • TreeMap implements Map interfaces.
  • TreeMap does not permit null keys. Instead, NullPointerException is thrown. Although, multiple null values can be associated with different keys.
  • TreeMap is a member of the Java Collections Framework.

Inheritance diagram of TreeMap

TreeMap inheritance diagram

TreeMap inheritance diagram




Constructors summary in TreeMap

  1. TreeMap(): constructs a new empty tree map, with the natural ordering of its keys.
  2. TreeMap(Comparator<? super K> comparator): constructs a new empty tree map, ordered according to the given comparator.
  3. TreeMap(Map<? extends K, ?extends V> m): constructs a new tree map that contains the same mappings as the given map, ordered according to the natural ordering of its keys.
  4. TreeMap(SortedMap<K, ? extends V> m): constructs a new tree map that contains the same mappings and uses the same ordering as the specified sorted map.

Methods in TreeMap class

  1. void clear(): deletes all elements in the tree map.
  2. Object clone(): returns a shallow copy of the TreeMap instance.
  3. Comprator<? super K> comparator: returns the comparator used to order the keys in the current map or null if the map uses the natural ordering of its keys.
  4. boolean containsKey(Object key): returns true if the specified key is present in the current tree map.
  5. boolean containsValue(Object value): returns true if the specified value is present to any one of the current’s map keys.
  6. V put(K key, V value): put the specified value to the specified key.
  7. V remove(Object key): removes the specified key from the current map.
  8. V replace(K key, V value): replaces the entry for the specified key only if it is currently mapped to some value.
  9. int size(): get the number of elements that the current tree map has.
  10. Collection<V> values(): returns a Collection view of the values contained in the current map.

For more information on the main methods of EnumSet, feel free to visit the original Oracle documentation.

Check whether a current tree map contains specified key or value using containsKey() and containsValue() and populating the TreeMap using put()

import java.util.*; 
  
public class TreeMapExample { 
    public static void main(String[] args) 
    { 
        TreeMap<Integer, String> treeMapExample =  
        new TreeMap<Integer, String>(); 
  
        // assing values to keys
        treeMapExample.put(5, "java"); 
        treeMapExample.put(15, "tutorial"); 
        treeMapExample.put(20, "dot"); 
        treeMapExample.put(25, "net"); 
  
        System.out.println("Current stage of the treeMap: " + treeMapExample); 
  
        // Checking for the key '15' 
        System.out.println("Is key 15 present in the map: " +  
        treeMapExample.containsKey(15); 
  
        // Checking for the key '5' 
        System.out.println("Is the key 5 present? " +  
        treeMapExample.containsKey(5)); 

        // Checking for value "java"
        System.out.println("Is the value 'java' present? " +  
        treeMapExample.containsValue("java")); 

        // Checking for value "tutorial"
        System.out.println("Is the value 'tutorial' present? " +  
        treeMapExample.containsValue("tutorial"));
    } 
}

Output:

Is the key 15 present? true
Is the key 5 present? true
Is the value 'java' present? true
Is the value 'tutorial' present? true

Removing an element from the TreeMap using remove()

import java.util.*;  
public class treeMapExample {  
   public static void main(String args[]) {  
    TreeMap<Integer,String> treeMap=new TreeMap<Integer,String>();    
      // populating the tree map using put()
      map.put(5,"Joe");    
      map.put(10,"Mike");    
      map.put(15,"Antony");    
      System.out.println("Before remove(): ");  
      // looping through the tree map so we can get each element
      for(Map.Entry m:map.entrySet())  
      {  
          // print key and value
          System.out.println(m.getKey()+" "+m.getValue());      
      }  
      map.remove(15);      
      System.out.println("After remove(): ");  
      for(Map.Entry m:map.entrySet())  
      {  
           // print key and value
          System.out.println(m.getKey()+" "+m.getValue());      
      }  
      }  
}

Output:

Before remove:
5 Joe
10 Mike
15 Antony
After Remove
5 Joe
10 Mike

 

 

 

Leave a Reply

avatar