- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 replace key and value in HashMap with identical key and different values
Create a HashMap and set key-value pair −
Map<Integer, String>map = new HashMap<>(); map.put(10, "A"); map.put(20, "B"); map.put(30, "C"); map.put(40, "D"); map.put(50, "E"); map.put(60, "F"); map.put(70, "G"); map.put(80, "H");
Now, let’s say you need to set a different value for an identical key. For that, use put() −
map.put(30, "T");
Example
import java.util.HashMap; import java.util.Map; public class Demo { public static void main(String args[]) { Map<Integer, String>map = new HashMap<>(); map.put(10, "A"); map.put(20, "B"); map.put(30, "C"); map.put(40, "D"); map.put(50, "E"); map.put(60, "F"); map.put(70, "G"); map.put(80, "H"); System.out.println("Map = \t" + map); map.put(30, "T"); System.out.println("Updated Map = \t" + map); } }
Output
Map = {80=H, 50=E, 20=B, 70=G, 40=D, 10=A, 60=F, 30=C} Updated Map = {80=H, 50=E, 20=B, 70=G, 40=D, 10=A, 60=F, 30=T}
- Related Articles
- Java Program to create a HashMap and add key-value pairs
- Java Program to remove key value pair from HashMap?
- Java Program to Update value of HashMap using key
- Java Program to Get key from HashMap using the value
- Get the value associated with a given key in Java HashMap
- Modify the value associated with a given key in Java HashMap
- How to use null value as key in Java HashMap
- Java Program to remove a key from a HashMap
- Java Program to remove a key from a HashMap only if it is associated with a given value
- Update key value where different key equals some value in MongoDB?
- Check if a given key exists in Java HashMap
- Why String class is popular key in a HashMap in Java?
- Create a TreeMap in Java and add key-value pairs
- How to sort Map values by key in Java?
- Replace null values with default value in Java Map

Advertisements