How to Update the Value for an Existing Key in a TreeMap Using put()?
Last Updated :
14 Feb, 2024
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:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args)
{
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put( 1 , "GeeksForGeeks" );
treeMap.put( 2 , "DSA Tutorial" );
treeMap.put( 3 , "Java Tutorial" );
treeMap.put( 4 , "Python Tutorial" );
System.out.println( "Oringinal TreeMap:" +treeMap);
treeMap.put( 2 , "Full Stack Web Development" );
System.out.println( "Updated TreeMap:" +treeMap);
}
}
|
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.
Share your thoughts in the comments
Please Login to comment...