Java : How to Remove Elements from HashMap while Iterating

HashMap:

Since Java 1.2, HashMap has been a part of the Java collection. This class is frequently found in the java.util package. In its most basic form, it implements the Java Map interface. It stores the data in (Key, Value) pairs that can be accessed using another type of index (e.g. an Integer). One object functions as a key (index) for another (value). If you try to insert a replica key, it will replace the element of the corresponding key.

HashMaps and HashTables are similar, but they are not synchronised. It also supports the storage of null keys, but only one null key object and any number of null values are permitted. This class makes no guarantees about the order of the map. To use this class and its methods, you must import java.util. The superclass of HashMap or the HashMap package.

Examples:

Input:

hashmap={"hello" : 2
                  "this" : 3
                  "BTechGeeks" :4
                 "Python" : 6
                 "Online" : 7
                 "Platform" : 9}

Output:

{Platform=9, this=3, Online=7}

Remove Elements from HashMap while Iterating

There are two ways to remove elements from hashmap while iterating they are:

Method #1:Using Keyset

HashMap’s keyset() method returns a set of keys that are backed by HashMap, which means that any items removed from the Key Set are also removed from HashMap.

So, using the KeySet Iterator, iterate over the HashMap and remove all the elements whose value is even.

Below is the implementation:

import java.util.*
import java.lang.*
import java.io.*


class Codechef


{
    public static void main(String[] args) throws java.lang.Exception
    {

        // create a map which has string as keys and Integer as values
        // initilaize it with some random keys and values
        HashMap < String, Integer > stringmap
        = new HashMap < String, Integer > () {
            {
                put("hello", 2)
                put("this", 3)
                put("BTechGeeks", 4)
                put("Python", 6)
                put("Online", 7)
                put("Platform", 9)
            }
        }
        // using keyset and initializing iterator to stringmap
        Iterator < String > itr = stringmap.keySet().iterator()
        // Traverse the elements
        while (itr.hasNext()) {
            // getting key of given stringmap
            String hashkey = itr.next()
            // checking if the value of hashkey is even
            if (stringmap.get(hashkey) % 2 == 0) {
                // remove the element from the stringmap
                itr.remove()
            }
        }
        // printing the stringmap
        System.out.println(stringmap)
    }
}

Output:

{Platform=9, this=3, Online=7}

Method #2:Using EntrySet

HashMap member function entrySet() returns a set of EntryK,V> in the HashMap, which is backed by HashMap, which means that any items excluded from the Entry Set will also be removed from HashMap.

So, when iterating over the HashMap, let’s delete all the elements with are divisible by 2.

Below is the implementation:

import java.io.*;
import java.lang.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Predicate;

class Codechef {
    public static void main(String[] args)
        throws java.lang.Exception
    {

        // create a map which has string as keys and Integer
        // as values
        // initilaize it with some random keys and values
        HashMap<String, Integer> stringmap
            = new HashMap<String, Integer>() {
                  {
                      put("hello", 2);
                      put("this", 3);
                      put("BTechGeeks", 4);
                      put("Python", 6);
                      put("Online", 7);
                      put("Platform", 9);
                  }
              };
        // Make an Iterator for the HashMap stringmap
        Iterator<Entry<String, Integer> > entryiterator
            = stringmap.entrySet().iterator();
        // Traverse the elements of hashmap
        while (entryiterator.hasNext()) {
            Entry<String, Integer> hashkey
                = entryiterator.next();
            // Cheecking if the given value is divisible by
            // 2
            if (hashkey.getValue() % 2 == 0) {
                // removing the element from the stringmap
                entryiterator.remove();
            }
        }
        // printing the stringmap
        System.out.println(stringmap);
    }
}

Output:

{Platform=9, this=3, Online=7}

Related Programs: