Categories: Java

Treemap class in Java Collection Framework

Along with the AbstractMap Class, the TreeMap class in Java is used to implement the Map interface and NavigableMap. Depending on which constructor is used, the map is sorted based on the natural ordering of its keys or by a Comparator specified at map creation time.

TreeMap class declaration:
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable  

where,

  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.
The following are the most significant aspects of the Java TreeMap class:
  • Java TreeMap stores values according to the key. It extends the AbstractMap class and implements the NavigableMap interface.
  • It only has unique elements.
  • Java TreeMap does not support null keys, but it does support multiple null values.
  • Furthermore, Java TreeMap does not support synchronization.
  • Java TreeMap keeps ascending order.
TreeMap Constructors:
  • TreeMap()– It is used to create an empty tree map that will be sorted using the key’s natural order.
  • TreeMap(Comparator<? super K> comparator)– It’s used to build an empty tree-based map that will be sorted with the comparator comp.
  • TreeMap(Map<? extends K,? extends V> m)– It is used to populate a treemap with entries from m, which will be sorted following the keys’ natural order.
  • TreeMap(SortedMap<K,? extends V> m)– It is used to initialize a treemap using the SortedMap sm’s entries, which are sorted in the same order as sm.
TreeMap Methods:
MethodDescription
Map.Entry<K,V> ceilingEntry(K key)It returns the key-value pair with the smallest key, larger than or equal to the supplied key, or null if no such key exists.
K ceilingKey(K key)It returns the least key, the key that is greater than the supplied key, or null if no such key exists.
void clear()It clears a map of all key-value pairs.
Object clone()It returns a shallow copy of TreeMap instance.
Comparator<? super K> comparator()It returns the comparator that orders the keys, or null if the map utilizes natural ordering.
NavigableSet<K> descendingKeySet()It returns the opposite order. View of the keys contained in the map that is navigable.
NavigableMap<K,V> descendingMap()It returns the key-value pairs supplied in decreasing order.
Map.Entry firstEntry()It returns the key-value pair with the shortest key.
Map.Entry<K,V> floorEntry(K key)It returns the greatest key, one that is less than or equal to the supplied key, or null if no such key exists.
void forEach(BiConsumer<? super K,? super V> action)It executes the specified action for each map entry until all entries have been processed or the action throws an exception.
SortedMap<K,V> headMap(K toKey)It returns key-value pairs whose keys are strictly less than or equal to toKey.
NavigableMap<K,V> headMap(K toKey, boolean inclusive)It produces key-value pairs with keys that are less than (or equal to, if inclusive is true) toKey.
Map.Entry<K,V> higherEntry(K key)It returns the least key that is strictly greater than the given key, or null if no such key exists.
K higherKey(K key)It returns true if this map has a mapping for the supplied key.
Set keySet()It returns the set of keys that exist in the map.
Map.Entry<K,V> lastEntry()It returns the key-value pair with the greatest key, or null if no such key exists.
Map.Entry<K,V> lowerEntry(K key)It gives a key-value mapping for the greatest key strictly less than the specified key, or null if no such key exists.
K lowerKey(K key)It returns the greatest key that is strictly less than the given key, or null if no such key exists.
NavigableSet<K> navigableKeySet()It returns a NavigableSet representation of the keys in this map.
Map.Entry<K,V> pollFirstEntry()It deletes and returns the key-value mapping associated with the map’s least key, or null if the map is empty.
Map.Entry<K,V> pollLastEntry()It deletes and returns a key-value mapping associated with the map’s biggest key, or null if the map is empty.
V put(K key, V value)It adds the supplied value to the map with the specified key.
void putAll(Map<? extends K,? extends V> map)It copies all key-value pairs from one map to another.
V replace(K key, V value)It substitutes the provided value for the specified key.
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)It replaces the value of each element with the result of running the supplied function on that entry until all entries are processed or the method throws an exception.
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)It returns key-value pairs with keys ranging from toKey.
SortedMap<K,V> subMap(K fromKey, K toKey)It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap<K,V> tailMap(K fromKey)It returns key-value pairs with keys equal to or greater than fromKey.
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive)It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey.
boolean containsKey(Object key)It returns true if the map contains a mapping for the specified key.
boolean containsValue(Object value)It returns true if the map maps one or more keys to the specified value.
K firstKey()It is used to return the first (lowest) key currently in this sorted map.
V get(Object key)It is used to return the value to which the supplied key is mapped by the map.
K lastKey()It is used to return the last (highest) key currently in the sorted map.
V remove(Object key)It removes the supplied key’s key-value pair from the map.
Set<Map.Entry<K,V>> entrySet()It returns a set view of all the mappings in the map.
int size()The number of key-value pairs in the hashtable is returned.
Collection values()It gives you a collection view of the values in the map.
Example: Adding Elements

import java.util.*;

// Main class
class Coderz {

 // Main driver method
 public static void main(String args[])
 {
  // Default Initialization of a TreeMap
  TreeMap tmobj = new TreeMap();

  // Inserting the elements in TreeMap
  // using put() method
  tmobj.put(3, "Coderzpy");
  tmobj.put(2, "From");
  tmobj.put(1, "learning");


  // Printing the elements of  TreeMaps

  // Map 1
  System.out.println(tmobj);
 
 }
}
Output:
{1=learning, 2=From, 3=Coderzpy}
Example: Changing Elements

import java.util.*;

// Main class
class Coderz {

 // Main driver method
 public static void main(String args[])
 {
  // Default Initialization of a TreeMap
  TreeMap tmobj = new TreeMap();

  // Inserting the elements in TreeMap
  // using put() method
  tmobj.put(3, "Coderzpy");
  tmobj.put(2, "From");
  tmobj.put(1, "learning");


  // Printing the elements of  TreeMaps

  // Map 1
  System.out.println(tmobj);
  tmobj.put(2, "coding from");
  
        // Printing the updated elements of Map
        System.out.println(tmobj);
 
 }
}
Output:
{1=learning, 2=From, 3=Coderzpy}
{1=learning, 2=coding from, 3=Coderzpy}
Example: Removing Elements

import java.util.*;

// Main class
class Coderz {

 // Main driver method
 public static void main(String args[])
 {
  // Default Initialization of a TreeMap
  TreeMap tmobj = new TreeMap();

  // Inserting the elements in TreeMap
  // using put() method
  tmobj.put(3, "Coderzpy");
  tmobj.put(2, "From");
  tmobj.put(1, "learning");


  // Printing the elements of  TreeMaps

  // Map 1
  System.out.println(tmobj);
  tmobj.remove(2);
  
        // Printing the updated elements of Map
        System.out.println(tmobj);
 
 }
}
Output:
{1=learning, 2=From, 3=Coderzpy}
{1=learning, 3=Coderzpy}
Example: Iterating through the TreeMap

import java.util.*;

// Main class
class Coderz {

 // Main driver method
 public static void main(String args[])
 {
  
   TreeMap<Integer, String> tmobj
            = new TreeMap<Integer, String>();

  // Inserting the elements in TreeMap
  // using put() method
  tmobj.put(3, "Coderzpy");
  tmobj.put(2, "From");
  tmobj.put(1, "learning");

 for (Map.Entry mapElement : tmobj.entrySet()) {
  
            int key = (int)mapElement.getKey();
  
            // Finding the value
            String value = (String)mapElement.getValue();
  
            // Printing the key and value
            System.out.println(key + " : " + value);
        }
 
 }
}
Output:
1 : learning
2 : From
3 : Coderzpy

Note: also read about the HashMap class in Java Collection Framework

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago