Java Program to remove key value pair from HashMap?



Let’s say the following is our HashMap −

HashMap<String, String>map = new HashMap<String, String>();

Add key value pair to the HashMap −

map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); map.put("4", "D"); map.put("5", "E"); map.put("6", "F"); map.put("7", "G"); map.put("8", "H"); map.put("9", "I");

Now, use the remove() method to remove the key-value pair −

map.remove("5");

Example

 Live Demo

import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class Demo {    public static void main(String[] args) {       HashMap<String, String>map = new HashMap<String, String>();       map.put("1", "A");       map.put("2", "B");       map.put("3", "C");       map.put("4", "D");       map.put("5", "E");       map.put("6", "F");       map.put("7", "G");       map.put("8", "H");       map.put("9", "I");       System.out.println("HashMap...");       for (String res: map.keySet()) {          System.out.println(res);       }       map.remove("5");       System.out.println("Updated HashMap...");       for (String res: map.keySet()) {          System.out.println(res);       }       map.remove("8");       System.out.println("Updated HashMap...");       for (String res: map.keySet()) {          System.out.println(res);       }    } }

Output

HashMap... 1 2 3 4 5 6 7 8 9 Updated HashMap... 1 2 3 4 6 7 8 9 Updated HashMap... 1 2 3 4 6 7 9
Updated on: 2019-07-30T22:30:25+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements