VOOZH about

URL: https://www.geeksforgeeks.org/java/update-the-value-of-an-existing-key-in-a-linkedhashmap-in-java/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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:

  • Key-value pair: In a LinkedHashMap, all the data can be stored in the form of a key-value pair, where the key is a unique value for each element in the map and the value is assigned to a particular key.
  • KeySet: The KeySet in a LinkedHashMap is gathered using the method and returns a set of all keys in the map.
  • Insertion Order: The elements inserted into the LinkedHashMap are maintained in the order.
  • Double-LinkedList: LinkedHashMap uses the doubly-linked list to maintain the order of the elements.

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.

  • put(): This method can be used to add new key values to the map and also update the values if the key already exists.

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:


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:

  • This Java program demonstrates updating the value of an existing key in a LinkedHashMap.
  • It starts by creating a LinkedHashMap named "linkedHashMap" with some key-value pairs.
  • After printing the original map, it uses a method called "updateValue" to update the value associated with the key "Key2" to 22.
  • Finally, it prints the updated map. In simple terms, it's like having a list of things with names and changing the value associated with one of those names while keeping the rest unchanged.
Comment