Sunday, May 19, 2024
HomeJavaFind out how to Take away Entry (key/worth) from HashMap in Java...

Find out how to Take away Entry (key/worth) from HashMap in Java whereas Iterating? Instance Tutorial


Hi there guys, Are you able to take away a key whereas iterating over HashMap in Java? This is among the attention-grabbing interview questions in addition to a standard drawback Java builders face whereas writing code utilizing HashMap. Some programmers will say No, you can not take away parts from HashMap whereas iterating over it. It will fail quick and throw concurrent modification exceptions. They’re proper however not fully. It is true that the iterator of HashMap is a fail-fast iterator however you may nonetheless take away parts from HashMap whereas iterating through the use of Iterator’s take away() methodology. 
The ConcurrentModificationException comes while you use Map.take away(Object key) to take away a key. Keep in mind, while you take away a key, the mapping itself is eliminated i.e. each key and worth objects are faraway from Map and its dimension decreased by 1.

Listed below are the precise steps to take away parts from HashMap whereas Iterating

1. Get units of keys by calling the Map.keySet() methodology
2. Get the Iterator from this set by calling the iterator() methodology of the Set interface.
3. Iterate over Map utilizing this Iterator and whereas loop
4. Take away an entry from a map primarily based on matching key from set like you may evaluate the important thing from Set with the merchandise you need to take away through the use of Iterator.take away() methodology

Find out how to take away a key from HashMap in Java? Instance

Right here is an instance to take away keys from HashMap whereas iterating. On this instance, I’ve a Map of assorted Java and Spring certifications and their price like OCAJP (1Z0-808) price round 248 US {Dollars}, identical is for OCPJP 8 (1Z0-809), whereas Spring certifications supplied by Pivotal like Spring Skilled Certification Examination and Spring Internet Utility Developer Examination price round 200 USD every (see right here).

Whereas Iterating over Map, I evaluate the important thing with the OCMJEA (Oracle Licensed Grasp Java Enterprise Architect), and if the important thing matches then I take away it from the Map. 

Right here, I’ve used the take away() methodology of HashMap, therefore this program will throw ConcurrentModfiicationException.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/*
 * Java Program to take away mapping from HashMap whereas Iterating
 * utilizing Map.take away(Object key) methodology
 */
public class Foremost {

  public static void most important(String args[]) {
    
    Map<String, Integer> certificationCost = new HashMap<>();
    certificationCost.put("OCAJP 1Z0-808", 248);
    certificationCost.put("OCPJP 1Z0-809", 248);
    certificationCost.put("Spring Skilled Certification Examination", 200);
    certificationCost.put("Spring Internet Utility Developer Examination", 200);
    certificationCost.put("OCMJEA 1Z0-807", 600);
    
    
    // let's attempt to take away factor from Hashmap 
    // utilizing Map.take away(Object key) methodology
    // this is not going to work, will throw ConcurrentModfiicationException
    Set<String> setOfCertifications = certificationCost.keySet();
    
    for(String certificaiton : setOfCertifications){
      
      if(certificaiton.incorporates("OCMJEA")){
        certificationCost.take away(certificaiton);
      }
    }
  }
}

Output
Exception in thread "most important" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
    at java.util.HashMap$KeyIterator.subsequent(HashMap.java:1453)
    at Foremost.most important(Foremost.java:24)


You possibly can see the Iterator of HashMap throws java.util.ConcurrentModificationException 
as quickly as you attempt to take away an entry whereas iterating over Map as a result of the iterator is fail-fast. If this had been a ConcurentHashMap then it will not throw the ConcurrentModficationExcetpion. Now, let’s have a look at the proper technique to take away an entry from HashMap whereas iterating over it.

How to remove a mapping from HashMap in Java


The proper technique to Take away a key from HashMap whereas Iterating in Java

Right here is the proper technique to take away a key or an entry from HashMap in Java whereas iterating over it. This code makes use of Iterator and its take away() methodology to delete a key from HashMap. While you take away a key, the worth additionally will get faraway from HashMap i.e. it is a shortcut to take away an entry from HashMap in Java.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/*
 * Java Program to take away mapping from HashMap whereas Iterating
 * utilizing Iterator's take away() methodology
 */
public class Foremost {

  public static void most important(String args[]) {
    
    Map<String, Integer> certificationCost = new HashMap<>();
    certificationCost.put("OCAJP 1Z0-808", 248);
    certificationCost.put("OCPJP 1Z0-809", 248);
    certificationCost.put("Spring Skilled Certification Examination", 200);
    certificationCost.put("Spring Internet Utility Developer Examination", 200);
    certificationCost.put("OCMJEA 1Z0-807", 600);
    
    // Map - earlier than eradicating a mapping
    System.out.println("earlier than: " + certificationCost);
    
    // let's use Iterator to take away a key from HashMap whereas iterating
    Iterator<String> iterator = certificationCost.keySet().iterator();
    
    whereas(iterator.hasNext()){
      String certification = iterator.subsequent();
      if(certification.incorporates("OCMJEA")){
        iterator.take away();
      }
    }
    
    // Map - after eradicating a mapping
    System.out.println("after: " + certificationCost);
  }
}

Output
earlier than: {Spring Skilled Certification Examination=200, OCMJEA 1Z0-807=600,
 Spring Internet Utility Developer Examination=200, OCPJP 1Z0-809=248,
 OCAJP 1Z0-808=248}
after: {Spring Skilled Certification Examination=200,
 Spring Internet Utility Developer Examination=200, OCPJP 1Z0-809=248,
 OCAJP 1Z0-808=248}

From the output you may see that the entry related to the “OCMJEA 1Z0-807” secret’s faraway from the Map, there have been 4 entries earlier than removing and now there are solely three entries remaining. Additionally, there isn’t a ConcurrentModificationException happens.

Java 8 Information
In Java 8 you need to use the map.values().removeAll(Collections.singleton(240)); to take away all key/worth pairs the place worth is 240. See these Java 8 tutorials and programs to be taught extra about new strategies added into current interfaces in JDK 8.

That is all about the way to take away a key or an entry/mapping whereas iterating over HashMap in Java. You can’t take away an entry whereas looping over Map however you may take away a key or worth whereas iterating over it. Since Iterator of HashMap is fail-fast it can throw ConcurrentModificationException if you happen to attempt to take away entry utilizing Map.take away(Object key) methodology, the correct technique to take away an entry from the HashMap through the use of Iterator’s take away() methodology.

Different Java Assortment Articles You Could like

Thanks for studying this text this far. For those who like this Java Assortment tutorial then please share it with your mates and colleagues. If in case you have any questions or suggestions then please drop a remark.

P. S. – If you wish to be taught HashMap and different Java collections in depth and in search of assets, it’s also possible to checkout this checklist of greatest Java Collections and Stream programs the place I’ve shared participating on-line programs to be taught Java Collections framework in depth. 
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments