How does TreeMap Handle Duplicate Keys in Java ?
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
namedtreeMap
. - Key-value pairs are added to the
treeMap
. - An attempt is made to insert a duplicate key
2
with the value"New Two"
. SinceTreeMap
does not allow duplicate keys, the existing value associated with key2
(“Two”) will be replaced by the new value (“New Two”). - The contents of the
treeMap
are displayed.
Contact Us