Remove Key from HashMap if Associated with Given Value in Java



Use the remove() method to remove a key only if it is associated with a given value.

Let’s say the following is our HashMap −

// 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));

Here, we are removing a key “Belt” only if it is associated with the given value 600 −

hm.remove("Belt", 600);

The following is an example to remove a key only if it is associated with a given value −

Example

 Live Demo

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));
      System.out.println("Elements in HashMap...");
      System.out.println(hm);
      // removing a key
      hm.remove("Wallet");
      System.out.println("\nUpdated HashMap after removing a key...");
      System.out.println(hm);
      // removing a key from a HashMap only if it is associated with a given value
      hm.remove("Belt", 600);
      System.out.println("\nUpdated HashMap after removing a key associated with a given value...");
      System.out.println(hm);
   }
}

Output

Elements in HashMap...
[Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000]

Updated HashMap after removing an key...
[Frames=800, Belt=600, Bag=1100, Sunglasses=2000]

Updated HashMap after removing a key associated with a given value...
{Frames=800, Bag=1100, Sunglasses=2000}
Updated on: 2019-07-30T22:30:24+05:30

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements