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 program to update the value for
// An existing key in a TreeMap using put() method
import java.io.*;
import java.util.*;
// Driver Class
class GFG {
// Main Function
public static void main (String[] args)
{
// Creating the TreeMap
TreeMap<Integer, String> treeMap = new TreeMap<>();
// Inserting the key-pair values into the treeMap
treeMap.put(1,"GeeksForGeeks");
treeMap.put(2,"DSA Tutorial");
treeMap.put(3,"Java Tutorial");
treeMap.put(4,"Python Tutorial");
// Print the oringinal TreeMap
System.out.println("Oringinal TreeMap:"+treeMap);
// Updating the values for an existing key
treeMap.put(2,"Full Stack Web Development");
// Print the updated TreeMap
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.