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
Modify the value associated with a given key in Java HashMap
First, create a HashMap and add elements to it −
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Now, to modify the value associated with a given key, use the put() method. Here, we are modifying the value for the key “Frames” −
hm.put("Frames", "900");
The following is an example to modify the value associated with a given key −
Example
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
// Get a set of the entries
Set set = hm.entrySet();
System.out.println("Elements in HashMap...");
System.out.println(set);
hm.put("Frames", "900");
System.out.println("\nUpdated HashMap Elements...");
System.out.println(hm);
}
}
Output
Elements in HashMap...
[Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000]
Updated HashMap Elements...
{Frames=900, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000}Advertisements