Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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
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
Advertisements