Remove value from HashMap in Java


Use the remove() method to remove value from HashMap.

First, create a HashMap and add elements −

HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));

Now, remove a value, let’s say with key “Wallet” −

Object ob = hm.remove("Wallet");

The following is an example to remove a value from HashMap −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      hm.put("Backpack", new Integer(1200));
      System.out.println("Map = "+hm);
      Object ob = hm.remove("Wallet");
      System.out.println("Map after removing an element= "+hm);
   }
}

Output

Map = {Backpack=1200, Belt=600, Wallet=700}
Map after removing an element= {Backpack=1200, Belt=600}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

595 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements