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

 Live Demo

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}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements