- 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}
Advertisements