What is Treemap in Java?

The Java TreeMap class implements a red-black tree. It allows for the efficient storage of key-value pairs in sorted order.

In Java, the TreeMap class is used to implement the Map interface, as well as the NavigableMap and AbstractMap classes. Depending on which function Object() { [native code] } is used, the map is sorted according to the natural ordering of its keys or by a Comparator specified at map formation time. This turns out to be an efficient method of sorting and storing key-value pairs. The storage order maintained by the treemap, like any other sorted map, must be consistent with equals, regardless of the specified comparators. The treemap implementation is not synchronized in the sense that if a map is visited by multiple threads concurrently and at least one of the threads modifies the map structurally, the map must be externally synchronized.

The following are the most significant aspects of the Java TreeMap class:

  • It extends the AbstractMap class and implements the NavigableMap interface. Java TreeMap only has unique elements.
  • TreeMap does not support null keys, but it does support multiple null values.
  • Java TreeMap does not support synchronization.
  • Java TreeMap keeps ascending order.

Constructors of TreeMap class

  • TreeMap(): It’s used to create an empty tree map that will be sorted according to the key’s natural order.
  • TreeMap(Comparator <? super K> comparator): It’s used to make a blank tree-based map that’ll be sorted with the comparator comp.
  • TreeMap(Map <? extends K, extends V> m): It’s used to populate a treemap with entries from m, which will be arranged according to the keys’ natural order.
  • TreeMap(SortedMap <K, extends V> m): It’s used to populate a treemap with entries from the SortedMap sm, which are then sorted in the same order as sm.

Most Used Methods of Java TreeMap class

MethodDescription
Map.Entry<K, V> ceilingEntry(K key)Returns the key-value pair with the smallest key that is bigger than or equal to the supplied key, or null if no such key exists.
K ceilingKey(K key)Returns the least key, the key that is greater than the supplied key, or null if no such key exists.
void clear()Cleans up a map by removing all key-value pairs.
Object clone()Returns a TreeMap instance that is a shallow replica of the original.
NavigableSet <K> descendingKeySet()Returns a reversal of the previous order. The keys in the map are displayed in a navigableSet view.
NavigableMap <K, V> descendingMap()In descending order, it returns the supplied key-value pairs.
Map.Entry firstEntry()Gives you the key-value pair with the smallest key.
Map.Entry <K,V> floorEntry(K key)Returns the greatest key, which must be less than or equal to the specified key, or null if no such key exists.
void forEach(BiConsumer <? super K,? super V> action)Performs the provided action for each map entry until the action throws an exception or all entries are processed.
SortedMap <K,V> headMap(K toKey)Returns key-value pairs with keys that are strictly less than or equal to toKey.
NavigableMap <K,V> headMap(K toKey, boolean inclusive)Returns key-value pairs with keys less (or equal to) toKey.
Map.Entry <K,V> higherEntry(K key)Returns null if no such key exists, or the least key is strictly greater than the specified key.
K higherKey(K key)Used to determine whether or not this map has a mapping for the given key.
Set keySet()Returns the set of keys that are present in the map.
Map.Entry <K,V> lastEntry()Returns the key-value pair with the largest key, or null if none exists.
Map.Entry<K,V> lowerEntry(K key)Returns either null if no such key exists, or a key-value mapping for the greatest key that is strictly less than the supplied key.

More Methods of Java TreeMap class

MethodDescription
V put(K key, V value)It populates the map with the provided value for the specified key.
void putAll(Map <? extends K,? extends V> map)It’s used to transfer all of the key-value pairs from one map to another.
V replace(K key, V value)It substitutes a specified key for the provided value.
boolean replace(K key, V oldValue, V newValue)For a given key, it replaces the previous value with the new value.
void replaceAll(BiFunction <? super K,? super V,? extends V> function)Until all entries have been processed or the function throws an error, it replaces each entry’s value with the result of running the specified function on that entry.
NavigableMap <K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)It returns key-value pairs from fromKey to toKey as keys.
SortedMap <K,V> subMap(K fromKey, K toKey)Returns key-value pairs with keys ranging from inclusive to exclusive, from fromKey to toKey.
SortedMap <K,V> tailMap(K fromKey)Returns key-value pairs with keys equal to or greater than fromKey.
NavigableMap <K,V> tailMap(K fromKey, boolean inclusive)Produces key-value pairs with keys bigger than (or equal to) fromKey (if inclusive is true).
boolean containsKey(Object key)If the map includes a mapping for the supplied key, it returns true.
boolean containsValue(Object value)If the map maps one or more keys to the supplied value, it returns true.
K firstKey()Used to return the current sorted map’s first (lowest) key.
V get(Object key)Used to get the value that the map maps the given key to.
K lastKey()Utilized to get the most recent (highest) key in the sorted map.
V remove(Object key)Removes the supplied key’s key-value pair from the map.
Set <Map.Entry<K,V>> entrySet()Gives you a set view of all the mappings on the map.
int size()The hashtable’s number of key-value pairs is returned.
Collection values()Gives you a collection view of all the values on the map.

Java TreeMap Examples

Example 01:

import java.util.*;  
class Tree_Map{  
public static void main(String args[]){  
   TreeMap<Integer,String> map=new TreeMap<Integer,String>();    
      map.put(93,"Afghanistan");    
      map.put(213,"Algeria");    
      map.put(55,"Brazil");       
        
      for(Map.Entry mapTree:map.entrySet()){    
       System.out.println(mapTree.getKey()+" "+mapTree.getValue());    
      }    
}  
}  

Output:

img-1

Example 02: remove()

import java.util.*;  
class Tree_Map_Remove {  
   public static void main(String args[]) {  
    TreeMap<Integer,String> map=new TreeMap<Integer,String>();    
      map.put(93,"Afghanistan");    
      map.put(213,"Algeria");    
      map.put(55,"Brazil");       
    
      System.out.println("Before remove() method");  
      for(Map.Entry mapTree:map.entrySet())  
      {  
          System.out.println(mapTree.getKey()+" "+mapTree.getValue());      
      }  
      map.remove(213);      
      System.out.println("After remove() method");  
      for(Map.Entry mapTree:map.entrySet())  
      {  
          System.out.println(mapTree.getKey()+" "+mapTree.getValue());      
      }  
      }  
}  

Output:

img-2

Example 03: NavigableMap

import java.util.*;  
class Navigable_Tree_Map{  
public static void main(String args[]){  
   NavigableMap<Integer,String> map=new TreeMap<Integer,String>();    
      map.put(93,"Afghanistan");    
      map.put(213,"Algeria");    
      map.put(55,"Brazil");    
      map.put(33,"France"); 
      map.put(49,"Germany"); 
      map.put(354,"Iceland"); 
     
      System.out.println("Navigable Map in Decending Order: "+map.descendingMap());  
  
      System.out.println("Navigable Map using headMap() method: "+map.headMap(49,true));  
  
      System.out.println("Navigable Map using tailMap() method: "+map.tailMap(49,true));
 
      System.out.println("Navigable Map using subMap() method: "+map.subMap(33, false, 55, true));   
}  
}  

Output:

img-3

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. What is a Thread in Java?

Leave a Comment