VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-update-the-value-for-an-existing-key-in-a-treemap-using-put/

⇱ How to Update the Value for an Existing Key in a TreeMap Using put()? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Update the Value for an Existing Key in a TreeMap Using put()?

Last Updated : 23 Jul, 2025

TreeMap is a part of Java Collection that can in-built class of java.util package. In Java, TreeMap is a pre-defined class that implements the NavigableMap interface and extends the AbstractMap class.

  • It represents the Key-Value pairs.
  • It is part of the Java Collection Framework.
  • It is a sorted map based on a red-black tree data structure.

In this article, we will be learning how to update the value for an existing key in a TreeMap using the basic put() method in Java.

Syntax of put() method:

TreeMap.put(key, value)

Where,

  • key: It refers to the key element that needs to be inserted into the TreeMap.
  • value: It refers to the value of the mapping key.

Program to Update the Value for an Existing Key in a TreeMap

This method is very simple, and it allows to insertion of a new value for an existing key by using the put() method.

Below is the Program to Update the Value for an Existing Key in a TreeMap Using put() in Java:


Output
Oringinal TreeMap:{1=GeeksForGeeks, 2=DSA Tutorial, 3=Java Tutorial, 4=Python Tutorial}
Updated TreeMap:{1=GeeksForGeeks, 2=Full Stack Web Development, 3=Java Tutorial, 4=Python Tutorial}


Explanation of the above Program:

  • The value for key 2 in the treeMap is used in this program through the usage of the put() method.
  • Then it replaced with Full Stack web Development and the original value DSA Tutorial.
  • At last, it prints the updated TreeMap.
Comment