Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Removing all Mapping From HashMap in Java
Next article icon

Removing all Mapping From HashMap in Java

Last Updated : 17 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Maps are used for when you want to associate a key with a value and Lists are an ordered collection. Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap is efficient for locating a value based on a key and inserting and deleting values based on a key.

For removing all mappings from a HashMap in java we can use various approaches :

  1. clear() method
  2. remove through iterator
  3. removeIf() method

Method 1: Using clear() method

The java.util.HashMap.clear() method in Java is used to clear and remove all the elements or mappings from a specified HashMap.

Syntax:

Hash_Map.clear()
Java
// Java program to remove mappings from // HashMap using clear() method  import java.io.*;  import java.util.*; class GFG {     public static void main(String[] args)     {          HashMap<String, Integer> gfg = new HashMap<>();          // adding values in hashMap 1         gfg.put("DSA", 100);         gfg.put("Problem Solving", 100);         gfg.put("Development", 99);         gfg.put("Interviews", 99);         gfg.put("Competitive Programming", 97);         gfg.put("FANG", 99);          // printing the size and elements         System.out.println("-------before removing------");         System.out.println(gfg);         System.out.println(gfg.size());          // clear() method         gfg.clear();          System.out.println("--------After removing-------");         System.out.println(gfg);         System.out.println(gfg.size());     } } 

Output
-------before removing------  {DSA=100, FANG=99, Competitive Programming=97, Problem Solving=100, Development=99, Interviews=99}  6  --------After removing-------  {}  0

Method 2: remove through the iterator

  • In this approach, you will iterate over the Map using iterator and then call remove on the iterator.
  • In this case, we are iterating over keys obtained from the calling keySet() method.
  • hasNext() is used to check whether there is a next element present inside the collection or not.
Java
// Java program to remove each key value pair // by iterating over the Hashmap  import java.io.*; import java.util.*; class GFG {     public static void main(String[] args)     {         HashMap<String, Integer> gfg = new HashMap<>();          // adding values in hashMap 1         gfg.put("DSA", 100);         gfg.put("Problem Solving", 100);         gfg.put("Development", 99);         gfg.put("Interviews", 99);         gfg.put("Competitive Programming", 97);         gfg.put("FANG", 99);          // printing the size and elements         System.out.println("-------before removing------");         System.out.println(gfg);         System.out.println(gfg.size());          // getting all keys of map using keySet()          Set keyset = gfg.keySet();          // iterating over the keys and removing         // hasNext() method is used to check whether next         // element present inside the collection or not          Iterator itr = keyset.iterator();         while (itr.hasNext()) {             itr.next();             itr.remove();         }          System.out.println("--------After removing-------");         System.out.println(gfg);         System.out.println(gfg.size());     } } 

Output
-------before removing------  {DSA=100, FANG=99, Competitive Programming=97, Problem Solving=100, Development=99, Interviews=99}  6  --------After removing-------  {}  0

Method 3: Using removeIf() method

Syntax:

public boolean removeIf(Predicate filter)

Parameter: This method takes a parameter filter which represents a predicate which returns true for elements to be removed.

Returns: This method returns True if the predicate returns true, and we are able to remove elements.

Exception: This method throws NullPointerException if the specified filter is null.

  • In this method, you need to specify the condition on which the element will be removed but for our case, we need to remove all elements.
  • Hence, we need to iterate on every key in entryset. We will check the set of keys obtained using the keySet() method.
  • We are removing every key of entrySet which is present in keySet. Every entry object, 1 entry=1key+1 value.
  • keySet() gives all keys present inside the Map.
Java
// Java program to remove the hashings // from HashMap using removeIf()  import java.io.*;  import java.util.*;  public class GFG {     public static void main(String args[])     {          HashMap<String, Integer> gfg = new HashMap<>();          // adding values in hashMap 1         gfg.put("DSA", 100);         gfg.put("Problem Solving", 100);         gfg.put("Development", 99);         gfg.put("Interviews", 99);         gfg.put("Competitive Programming", 97);         gfg.put("FANG", 99);          System.out.println("-------before removing------");         System.out.println(gfg);         System.out.println(gfg.size());          // getting all the keys of map          Set<String> keySet = gfg.keySet();          // checking the entry set          // key in keySet and remove         // it one by one         gfg.entrySet().removeIf(             entry -> keySet.contains(entry.getKey()));          System.out.println("--------After removing-------");         System.out.println(gfg);         System.out.println(gfg.size());     } } 

Output
-------before removing------  {DSA=100, FANG=99, Competitive Programming=97, Problem Solving=100, Development=99, Interviews=99}  6  --------After removing-------  {}  0

Next Article
Removing all Mapping From HashMap in Java

R

rajatagrawal5
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-HashMap
Practice Tags :
  • Java

Similar Reads

    Creating HashMap from Other Maps in Java
    Map interface present in java.util package represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore, it behaves a bit differently from the rest of the collection types. A map contains unique keys. There are three main types of maps in
    3 min read
    Getting Synchronized Map from Java HashMap
    HashMap is a non synchronized collection class. If we want to perform thread-safe operations on it then we must have to synchronize it explicitly. In order to synchronize it explicitly the synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map back
    2 min read
    How to Remove Elements from a LinkedHashMap in Java?
    A LinkedHashMap is a part of the Collection Framework from java.util package Java and is similar to a HashMap, except that a LinkedHashMap preserves the insertion order among the keys/entries. In this article, we will look at how to remove the elements from a LinkedHashMap in Java. Program to Remove
    2 min read
    Traverse Through a HashMap in Java
    HashMap stores the data in (Key, Value) pairs, and you can access them by an index of another type. HashMap class implements Map interface which allows us to store key. hashMap is a part of the java collections framework been up since Java 1.2. It internally uses hashing technique which is pretty fa
    4 min read
    Getting Set View of Keys from HashMap in Java
    The HashMap class of Java provides the functionality of the hash table data structure. This class is found in the java.util package. It implements the Map interface. It stores elements in (Key, Value) pairs and you can access them by an index of another type (e.g. Integer/String). Here, keys are use
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences