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

  1. import java.util.*;
  2. public class HashMapRemoveExample {
  3. public static void main(String args[]) {
  4.  
  5. HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
  6.       hashMap.put(1, "One");
  7.       hashMap.put(2, "Two");
  8.       hashMap.put(3, "Three");
  9. System.out.println("Initial HashMap");
  10. System.out.println(hashMap);
  11.  
  12. hashMap.remove(1);
  13. System.out.println("HashMap after removing 1 element");
  14. System.out.println(hashMap);
  15.  
  16. hashMap.clear();
  17. System.out.println("HashMap after removing all elements");
  18. System.out.println(hashMap);
  19.  
  20. }
  21. }
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.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on