- Trending Categories
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 remove a key from a HashMap
To remove a key from HashMap, use the remove() method.
First, create a HashMap and add elements −
// 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));
Let us now remove a key −
hm.remove("Wallet");
The following is an example to remove a key from a HashMap −
Example
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); hm.remove("Wallet"); System.out.println("
Updated HashMap after removing a key..."); System.out.println(hm); } }
Output
Elements in HashMap... [Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000] Updated HashMap after removing a key... {Frames=800, Belt=600, Bag=1100, Sunglasses=2000}
- Related Articles
- Java Program to remove key value pair from HashMap?
- Java Program to remove a key from a HashMap only if it is associated with a given value
- Java Program to Get key from HashMap using the value
- Java Program to create a HashMap and add key-value pairs
- Remove value from HashMap in Java
- Remove a key from TreeMap in Java
- Java Program to Update value of HashMap using key
- Remove all values from HashMap in Java
- C++ Remove an Entry Using Key from HashMap while Iterating Over It
- Java Program to remove a key from a TreeMap only if it is associated with a given value
- Check if a given key exists in Java HashMap
- Java Program to Iterate over a HashMap
- Java Program to replace key and value in HashMap with identical key and different values
- Java Program to Remove a Sublist from a List
- How to remove a key from a python dictionary?

Advertisements