
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to update value of HashMap using key
HashMap is a part of the Java Collections Framework, and it is used for storing key-value pairs. In this article, we will see how to update the value of a HashMap using a key.
We will use following methods to update the value of a HashMap:
Using put() Method
The put() method is used to add a key-value pair to the HashMap. If the key already exists, it will update the value that is stored with that key.
Example
In the following example, we will create a HashMap and then update the value of a key using the put() method.
import java.util.HashMap; import java.util.Map; public class UpdateHash { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("Apple", 10); map.put("Banana", 20); map.put("Cherry", 30); System.out.println("Original Map: " + map); map.put("Banana", 25); System.out.println("Updated Map: " + map); } }
Output
Following is the output of the above code:
Original Map: {Apple=10, Banana=20, Cherry=30} Updated Map: {Apple=10, Banana=25, Cherry=25}
Using compute() Method
The compute() method is from the Map interface, and it is used for computing a new value for a key based on its current value. If the key does not exist, it will add the key with the computed value.
Example
In the following is the code to update the value of a HashMap using the compute() method.
import java.util.HashMap; import java.util.Map; public class UpdateHash { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("Apple", 10); map.put("Banana", 20); map.put("Cherry", 30); System.out.println("Original Map: " + map); map.compute("Banana", (key, value) -> value + 5); System.out.println("Updated Map: " + map); } }
Output
Following is the output of the above code:
Original Map: {Apple=10, Banana=20, Cherry=30} Updated Map: {Apple=10, Banana=25, Cherry=30}
Using replace() Method
Another way to update the value of a HashMap is to use the replace() method. If the key exists, it will update the value with the new value provided.
Example
In the following is the code to update the value of a HashMap using the replace() method.
import java.util.HashMap; import java.util.Map; public class UpdateHash { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("Apple", 10); map.put("Banana", 20); map.put("Cherry", 30); System.out.println("Original Map: " + map); map.replace("Banana", 25); System.out.println("Updated Map: " + map); } }
Output
Following is the output of the above code:
Original Map: {Apple=10, Banana=20, Cherry=30} Updated Map: {Apple=10, Banana=25, Cherry=30}