Open In App

How does TreeMap Handle Duplicate Keys in Java ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, when it comes to handling duplicate keys in a TreeMap, the class does not allow duplicate keys. If we try to insert a key-value pair with a key that already exists in the TreeMap, the new value will override the existing one associated with that key.

Declaration of a TreeMap:

TreeMap<KeyType, ValueType> treeMap = new TreeMap<>();

Program to Handle Duplicate Keys in a TreeMap in Java

Below is a demonstration of a Program to Handle Duplicate Keys in a TreeMap in Java:

Java




// Java program to handle duplicate keys in a TreeMap
import java.util.TreeMap;
class GFG {
     public static void main(String[] args) {
        // Creating a TreeMap
        TreeMap<Integer, String> treeMap = new TreeMap<>();
  
        // Adding key-value pairs
        treeMap.put(1, "One");
        treeMap.put(2, "Two");
        treeMap.put(3, "Three");
  
       // Attempting to add a duplicate key
        treeMap.put(2, "New Two"); // This will overwrite the value for key 2
  
  
        // Displaying the contents of the TreeMap
        System.out.println("TreeMap contents: " + treeMap);
    }
}


Output

TreeMap contents: {1=One, 2=New Two, 3=Three}


Explanation of the Program:

  • In the above program, it creates a TreeMap named treeMap.
  • Key-value pairs are added to the treeMap.
  • An attempt is made to insert a duplicate key 2 with the value "New Two". Since TreeMap does not allow duplicate keys, the existing value associated with key 2 (“Two”) will be replaced by the new value (“New Two”).
  • The contents of the treeMap are displayed.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads