VOOZH about

URL: https://www.geeksforgeeks.org/java/treemap-handle-duplicate-keys-in-java/

⇱ How does TreeMap Handle Duplicate Keys in Java ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How does TreeMap Handle Duplicate Keys in Java ?

Last Updated : 23 Jul, 2025

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:


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.
Comment