English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to update the value of Java HashMap using keys.
To understand this example, you should understand the followingJava ProgrammingTopic:
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); System.out.println("HashMap: " + numbers); //Return the value of the key Second int value = numbers.get("Second"); //Update the value value = value * value; //Insert the updated value into the HashMap numbers.put("Second", value); System.out.println("Updated HashMap: " + numbers); } }
Output Result
HashMap: {Second=2, Third=3, First=1} Updated HashMap: {Second=4, Third=3, First=1}
In the above example, we usedHashMap put()method to update the value of the key Second. Here, first, we useHashMap get()to access the value of the method .
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("First", 1); numbers.put("Second", 2); System.out.println("HashMap: " + numbers); // to update the value of Second // Using computeIfPresent() numbers.computeIfPresent("Second", (key, oldValue) -> oldValue * 2); System.out.println("Updated HashMap: " + numbers); } }
Output Result
HashMap: {Second=2, First=1} Updated HashMap: {Second=4, First=1}
In the above example, we used the computeIfPresent() method to recalculate the value of the key Second. For more information, please visitHashMap computeIfPresent().
In this case, we willLambda expressionis used as the method parameter.
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("First", 1); numbers.put("Second", 2); System.out.println("HashMap: " + numbers); //Update the value of 'First' //Using Merge() Method numbers.merge("First", 4, (oldValue, newValue) -> oldValue + newValue); System.out.println("Updated HashMap: " + numbers); } }
Output Result
HashMap: {Second=2, First=1} Updated HashMap: {Second=2, First=5}
In the above example, the merge() method adds the old value and new value of the key 'First' together. And, the updated value is inserted into the HashMap. For more information, please visitHashMap merge().