Features of a TreeMap

Some important features of the treemap are as follows: 

  1. This class is a member of the Java Collections Framework.
  2. The class implements Map interfaces including NavigableMap, SortedMap, and extends AbstractMap class.
  3. TreeMap in Java does not allow null keys (like Map) and thus a NullPointerException is thrown. However, multiple null values can be associated with different keys.
  4. Entry pairs returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method.

Now let us move forward and discuss Synchronized TreeMap. The implementation of a TreeMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the Collections.synchronizedSortedMap method. This is best done at the creation time, to prevent accidental unsynchronized access to the set. This can be done as:

SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...)); 

Geeks, now you must be wondering how does the TreeMap works internally? 

The methods in a TreeMap while getting keyset and values, return an Iterator that is fail-fast in nature. Thus, any concurrent modification will throw ConcurrentModificationException. A TreeMap is based upon a red-black tree data structure. 

Each node in the tree has: 

  • 3 Variables (K key=Key, V value=Value, boolean color=Color)
  • 3 References (Entry left = Left, Entry right = Right, Entry parent = Parent)

TreeMap in Java

The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the treemap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. The treemap implementation is not synchronized in the sense that if a map is accessed by multiple threads, concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally. 

The TreeMap in Java is a concrete implementation of the java.util.SortedMap interface. It provides an ordered collection of key-value pairs, where the keys are ordered based on their natural order or a custom Comparator passed to the constructor.

A TreeMap is implemented using a Red-Black tree, which is a type of self-balancing binary search tree. This provides efficient performance for common operations such as adding, removing, and retrieving elements, with an average time complexity of O(log n).

Here’s an example of how to use the TreeMap class:

Java




import java.util.Map;
import java.util.TreeMap;
 
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> treeMap = new TreeMap<>();
 
        // Adding elements to the tree map
        treeMap.put("A", 1);
        treeMap.put("C", 3);
        treeMap.put("B", 2);
 
        // Getting values from the tree map
        int valueA = treeMap.get("A");
        System.out.println("Value of A: " + valueA);
 
        // Removing elements from the tree map
        treeMap.remove("B");
 
        // Iterating over the elements of the tree map
        for (String key : treeMap.keySet()) {
            System.out.println("Key: " + key + ", Value: " + treeMap.get(key));
        }
    }
}


Output

Value of A: 1
Key: A, Value: 1
Key: C, Value: 3

Similar Reads

Features of a TreeMap

...

Constructors in TreeMap

Some important features of the treemap are as follows:...

Methods in the TreeMap Class

In order to create a TreeMap, we need to create an object of the TreeMap class. The TreeMap class consists of various constructors that allow the possible creation of the TreeMap. The following are the constructors available in this class:...

Performing Various Operations on TreeMap

...