Algorithm
-
Initialize HashMap:
- Create a HashMap instance.
-
Insert Key-Value Pairs:
- Add key-value pairs to the HashMap.
-
Prompt for Key and New Value:
- Take user input or set values for the key and the new value to be updated.
-
Check if Key Exists:
- Verify if the specified key exists in the HashMap.
-
Update Value:
- If the key is found, update the corresponding value with the new value.
-
Print Updated HashMap:
- Display the updated HashMap with the modified key-value pair.
Code Examples
#1 Code Example- Update value of HashMap using put()
Code -
Java Programming
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 key Second
int value = numbers.get("Second");
// update the value
value = value * value;
// insert the updated value to the HashMap
numbers.put("Second", value);
System.out.println("HashMap with updated value: " + numbers);
}
}
Copy The Code &
Try With Live Editor
Output
HashMap: {Second=2, Third=3, First=1}
HashMap with updated value: {Second=4, Third=3, First=1}
HashMap with updated value: {Second=4, Third=3, First=1}
#2 Code Example- Update value of HashMap using computeIfPresent()
Code -
Java Programming
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 Second
// Using computeIfPresent()
numbers.computeIfPresent("Second", (key, oldValue) -> oldValue * 2);
System.out.println("HashMap with updated value: " + numbers);
}
}
Copy The Code &
Try With Live Editor
Output
HashMap: {Second=2, First=1}
HashMap with updated value: {Second=4, First=1}
HashMap with updated value: {Second=4, First=1}
#3 Code Example- Update value of Hashmap using merge()
Code -
Java Programming
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 the merge() method
numbers.merge("First", 4, (oldValue, newValue) -> oldValue + newValue);
System.out.println("HashMap with updated value: " + numbers);
}
}
Copy The Code &
Try With Live Editor
Output
HashMap: {Second=2, First=1}
HashMap with updated value: {Second=2, First=5}
HashMap with updated value: {Second=2, First=5}
Demonstration
Java Programing Example to Update value of HashMap using key-DevsEnv