Open In App

How to Update the Value of an Existing Key in a LinkedHashMap in Java?

In Java programming, a LinkedHahMap is like HashMap with additional features in the Java Collections framework. It keeps track of the order in which elements were added. A regular HashMap doesn’t have a fixed order for elements. LinkedHashMap uses an approach with a doubly-linked list to remember the order of inserted keys.

Key terminologies:



Implementation to Update the Existing Keys

In Java, the implementation of the update of the values of an existing key in a LinkedHashMap using the put() method. It can be used to update the values of the existing key in the LinkedHashMap.

Example:

Input: Original LinkedHashMap: {Key1=1, Key2=2, Key3=3}



Output: Value updated for key ‘Key2’
Updated LinkedHashMap: {Key1=1, Key2=22, Key3=3}

Java Program to Update the Value of an Existing Key in a LinkedHashMap

Below is the implementation of Updating the Value of an Existing Key in a LinkedHashMap:




// Java Program to update the value of an existing key in a LinkedHashMap
import java.util.LinkedHashMap;
public class GFGUpdateLinkedHashMap 
{
    public static void main(String[] args) 
    {
        // Create a sample LinkedHashMap named as linkedHashMap
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
  
        // Add some key-value pairs
        linkedHashMap.put("Key1", 1);
        linkedHashMap.put("Key2", 2);
        linkedHashMap.put("Key3", 3);
  
        // print the original map
        System.out.println("Original LinkedHashMap: " + linkedHashMap);
  
        // Update the existing value with the key "Two"
        updateValue(linkedHashMap, "Key2", 22);
  
        // print the updated map
        System.out.println("Updated LinkedHashMap: " + linkedHashMap);
    }
  
    // Method to update the existing key value in a LinkedHashMap
    private static <K, V> void updateValue(LinkedHashMap<K, V> map, K key, V newValue) 
    {
        if (map.containsKey(key)) 
        {
            map.put(key, newValue);
            System.out.println("Value updated for key '" + key + "'");
        } else 
        {
            System.out.println("Key '" + key + "' not found in the LinkedHashMap");
        }
    }
}

Output
Original LinkedHashMap: {Key1=1, Key2=2, Key3=3}
Value updated for key 'Key2'
Updated LinkedHashMap: {Key1=1, Key2=22, Key3=3}


Explanation of the Program:


Article Tags :