Remove HashMap elements
We can remove elements from HashMap using methods provided in it
There are 2 methods listed below which can be used to remove elements from HashMap
Object remove(Object key)
Removes the mapping for the specified key from this map if present.
Void clear()
Removes all of the mappings from this map
Example
- import java.util.*;
- public class HashMapRemoveExample {
- public static void main(String args[]) {
- HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
- hashMap.put(1, "One");
- hashMap.put(2, "Two");
- hashMap.put(3, "Three");
- System.out.println("Initial HashMap");
- System.out.println(hashMap);
- hashMap.remove(1);
- System.out.println("HashMap after removing 1 element");
- System.out.println(hashMap);
- hashMap.clear();
- System.out.println("HashMap after removing all elements");
- System.out.println(hashMap);
- }
- }
import java.util.*; public class HashMapRemoveExample { public static void main(String args[]) { HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); hashMap.put(1, "One"); hashMap.put(2, "Two"); hashMap.put(3, "Three"); System.out.println("Initial HashMap"); System.out.println(hashMap); hashMap.remove(1); System.out.println("HashMap after removing 1 element"); System.out.println(hashMap); hashMap.clear(); System.out.println("HashMap after removing all elements"); System.out.println(hashMap); } }
We can see that, clear() method has removed all elements in HashMap and remove() method has removed only specified element from the map.