Performing Various Operations on TreeMap

After the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the TreeMap. Now, let’s see how to perform a few frequently used operations on the TreeMap.

Operation 1: Adding Elements

In order to add an element to the TreeMap, we can use the put() method. However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in ascending order. 

Example

Java




// Java Program to Illustrate Addition of Elements
// in TreeMap using put() Method
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
        // Default Initialization of a TreeMap
        TreeMap tm1 = new TreeMap();
 
        // Inserting the elements in TreeMap
        // using put() method
        tm1.put(3, "Geeks");
        tm1.put(2, "For");
        tm1.put(1, "Geeks");
 
        // Initialization of a TreeMap using Generics
        TreeMap<Integer, String> tm2
            = new TreeMap<Integer, String>();
 
        // Inserting the elements in TreeMap
        // again using put() method
        tm2.put(new Integer(3), "Geeks");
        tm2.put(new Integer(2), "For");
        tm2.put(new Integer(1), "Geeks");
 
        // Printing the elements of both TreeMaps
 
        // Map 1
        System.out.println(tm1);
        // Map 2
        System.out.println(tm2);
    }
}


Output

{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

Operation 2: Changing Elements

After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the treemap are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.

Example

Java




// Java program to Illustrate Updation of Elements
// in TreeMap using put() Method
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
 
        // Inserting the elements in Map
        // using put() method
        tm.put(3, "Geeks");
        tm.put(2, "Geeks");
        tm.put(1, "Geeks");
 
        // Print all current elements in map
        System.out.println(tm);
 
        // Inserting the element at specified
        // corresponding to specified key
        tm.put(2, "For");
 
        // Printing the updated elements of Map
        System.out.println(tm);
    }
}


Output

{1=Geeks, 2=Geeks, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

Operation 3: Removing Element

In order to remove an element from the TreeMap, we can use the remove() method. This method takes the key value and removes the mapping for the key from this treemap if it is present in the map.

Example

Java




// Java program to Illustrate Removal of Elements
// in TreeMap using remove() Method
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
 
        // Inserting the elements
        // using put() method
        tm.put(3, "Geeks");
        tm.put(2, "Geeks");
        tm.put(1, "Geeks");
        tm.put(4, "For");
 
        // Printing all elements of Map
        System.out.println(tm);
 
        // Removing the element corresponding to key
        tm.remove(4);
 
        //  Printing updated TreeMap
        System.out.println(tm);
    }
}


Output

{1=Geeks, 2=Geeks, 3=Geeks, 4=For}
{1=Geeks, 2=Geeks, 3=Geeks}

Operation 4: Iterating through the TreeMap

There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method.

Example

Java




// Java Program to Illustrate Iterating over TreeMap
// using
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
 
        // Inserting the elements
        // using put() method
        tm.put(3, "Geeks");
        tm.put(2, "For");
        tm.put(1, "Geeks");
 
        // For-each loop for traversal over Map
        // via entrySet() Method
        for (Map.Entry mapElement : tm.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 : Geeks
2 : For
3 : Geeks

Advantages of TreeMap:

  1. Sorted order: The TreeMap provides a sorted order of its elements, based on the natural order of its keys or a custom Comparator passed to the constructor. This makes it useful in situations where you need to retrieve elements in a specific order.
  2. Predictable iteration order: Because the elements in a TreeMap are stored in a sorted order, you can predict the order in which they will be returned during iteration, making it easier to write algorithms that process the elements in a specific order.
  3. Search performance: The TreeMap provides an efficient implementation of the Map interface, allowing you to retrieve elements in logarithmic time, making it useful in search algorithms where you need to retrieve elements quickly.
  4. Self-balancing: The TreeMap is implemented using a Red-Black tree, which is a type of self-balancing binary search tree. This provides efficient performance for adding, removing, and retrieving elements, as well as maintaining the sorted order of the elements.

Disadvantages of TreeMap:

  1. Slow for inserting elements: Inserting elements into a TreeMap can be slower than inserting elements into a regular Map, as the TreeMap needs to maintain the sorted order of its elements.
  2. Key restriction: The keys in a TreeMap must implement the java.lang.Comparable interface, or a custom Comparator must be provided. This can be a restriction if you need to use custom keys that do not implement this interface.

Reference books:

“Java Collections” by Maurice Naftalin and Philip Wadler. This book provides a comprehensive overview of the Java Collections framework, including the TreeMap.

“Java in a Nutshell” by David Flanagan. This book provides a quick reference for the core features of Java, including the TreeMap.

“Java Generics and Collections” by Maurice Naftalin and Philip Wadler. This book provides a comprehensive guide to generics and collections in Java, including the TreeMap.



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

...