How does TreeMap Handle Duplicate Keys in Java ?
Last Updated :
12 Feb, 2024
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
import java.util.TreeMap;
class GFG {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put( 1 , "One" );
treeMap.put( 2 , "Two" );
treeMap.put( 3 , "Three" );
treeMap.put( 2 , "New Two" );
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.
Share your thoughts in the comments
Please Login to comment...