Saturday, November 9, 2019

How To Take Away Entry (Key/Value) From Hashmap Piece Iterating? Event Tutorial

Can yous take a cardinal piece iterating over HashMap inward Java? This is i of the interesting interview questions every bit good every bit a mutual occupation Java developer appear upwards piece writing code using HashMap. Some programmer volition nation No, yous cannot take elements from HashMap piece iterating over it. This volition neglect fast as well as throw concurrent alteration exception. They are right simply non completely. It's truthful that the iterator of HashMap is a fail-fast iterator simply yous tin withal take elements from HashMap piece iterating past times using Iterator's remove() method. This is the same technique which nosotros convey used inward past times to take elements piece iterating over a List inward Java. The cardinal hither is non to purpose the remove() method from Map or List interface to avoid java.util.ConcurrentModfiicationException inward Java.

The ConcurrentModificationException comes when yous use Map.remove(Object key) to take a key. Remember, when yous take a key, the mapping itself is removed i.e. both cardinal as well as value objects are removed from Map as well as its size reduced past times 1.

Here are the exact steps to take elements from HashMap piece Iterating

1. Get sets of keys past times calling the Map.keySet() method
2. Get the Iterator from this laid upwards past times calling iterator() method of the Set interface.
3. Iterate over Map using this Iterator as well as piece loop
4. Remove an entry from a map based on matching cardinal from laid upwards e.g. yous tin compare the cardinal from Set amongst the especial yous desire to take past times using Iterator.remove() method


Here is an event to remove elements from HashMap piece iterating. In this example, I convey a Map of diverse Java as well as Spring certifications as well as their terms e.g OCAJP (1Z0-808) terms some 248 U.S. Dollars, same is for OCPJP 8 (1Z0-809), piece Spring certifications provided past times Pivotal e.g. Spring Professional Certification Exam as well as Spring Web Application Developer Exam terms some 200 USD each (see here).

While Iterating over Map, I compare cardinal amongst the OCMJEA (Oracle Certified Master Java Enterprise Architect) as well as if the cardinal matches as well as so I take it from the Map. Here, I convey used the remove() method of HashMap, thence this programme volition throw ConcurrentModfiicationException.

import java.util.HashMap; import java.util.Map; import java.util.Set;   /*  * Java Program to take mapping from HashMap piece Iterating  * using Map.remove(Object key) method  */ public class Main {    public static void main(String args[]) {          Map<String, Integer> certificationCost = new HashMap<>();     certificationCost.put("OCAJP 1Z0-808", 248);     certificationCost.put("OCPJP 1Z0-809", 248);     certificationCost.put("Spring Professional Certification Exam", 200);     certificationCost.put("Spring Web Application Developer Exam", 200);     certificationCost.put("OCMJEA 1Z0-807", 600);               // let's endeavour to take chemical component division from Hashmap using Map.remove(Object key) method     // this volition non work, volition throw ConcurrentModfiicationException     Set<String> setOfCertifications = certificationCost.keySet();          for(String certificaiton : setOfCertifications){              if(certificaiton.contains("OCMJEA")){         certificationCost.remove(certificaiton);       }     }   } }  Output Exception inward thread "main" java.util.ConcurrentModificationException     at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)     at java.util.HashMap$KeyIterator.next(HashMap.java:1453)     at Main.main(Main.java:24)

You tin run into the Iterator of HashMap throws java.util.ConcurrentModificationException every bit presently every bit yous endeavour to take an entry piece iterating over Map because the iterator is fail-fast. If this had been a ConcurentHashMap as well as so it won't throw the ConcurrentModficationExcetpion. Now, let's run into the right agency to take an entry from HashMap piece iterating over it.




Right agency to Remove a cardinal from HashMap piece Iterating inward Java

Here is the right agency to take a cardinal or an entry from HashMap inward Java piece iterating over it. This code uses Iterator as well as its remove() method to delete a cardinal from HashMap. When yous take a key, the value likewise gets removed from HashMap i.e. it's a shortcut to take an entry from HashMap inward Java.

import java.util.HashMap; import java.util.Iterator; import java.util.Map;   /*  * Java Program to take mapping from HashMap piece Iterating  * using Iterator's remove() method  */ public class Main {    public static void main(String args[]) {          Map<String, Integer> certificationCost = new HashMap<>();     certificationCost.put("OCAJP 1Z0-808", 248);     certificationCost.put("OCPJP 1Z0-809", 248);     certificationCost.put("Spring Professional Certification Exam", 200);     certificationCost.put("Spring Web Application Developer Exam", 200);     certificationCost.put("OCMJEA 1Z0-807", 600);          // Map - earlier removing a mapping     System.out.println("before: " + certificationCost);          // let's purpose Iterator to take a cardinal from HashMap piece iterating     Iterator<String> iterator = certificationCost.keySet().iterator();          while(iterator.hasNext()){       String certification = iterator.next();       if(certification.contains("OCMJEA")){         iterator.remove();       }     }          // Map - afterwards removing a mapping     System.out.println("after: " + certificationCost);   } }  Output before: {Spring Professional Certification Exam=200, OCMJEA 1Z0-807=600,  Spring Web Application Developer Exam=200, OCPJP 1Z0-809=248,  OCAJP 1Z0-808=248} after: {Spring Professional Certification Exam=200,  Spring Web Application Developer Exam=200, OCPJP 1Z0-809=248,  OCAJP 1Z0-808=248}

From the output yous tin run into that the entry associated amongst "OCMJEA 1Z0-807" cardinal is removed the Map, in that place were four entries earlier removal as well as immediately in that place are entirely 3 entries remaining. Also, in that place is no ConcurrentModificationException occurs.



Java 8 Facts
In Java 8 yous tin purpose the map.values().removeAll(Collections.singleton(240)); to take all key/value pairs where value is 240. See Java SE 8 for the Impatient to larn to a greater extent than close novel methods added into existing interfaces inward JDK 8.

 Can yous take a cardinal piece iterating over HashMap inward Java How to Remove Entry (key/value) from HashMap piece Iterating? Example Tutorial


That's all close how to take a cardinal or an entry/mapping piece iterating over HashMap inward Java. You cannot take an entry piece looping over Map simply yous tin take a cardinal or value piece iterating over it. Since Iterator of HashMap is fail-fast it volition throw ConcurrentModificationException if yous endeavour to take entry using Map.remove(Object key) method, the right agency to take an entry from the HashMap past times using Iterator's remove() method.


Further Learning
Java In-Depth: Become a Complete Java Engineer
25 Java Collection Interview Questions
How HashMap industrial plant inward Java
How ConcurrentHashMap industrial plant inward Java
Java Programming Interview Exposed past times Makhem

Thanks for reading this article this far. If yous similar this tutorial as well as so delight part amongst your friends as well as colleagues. IF yous convey whatever enquiry or feedback as well as so delight drib a comment.

No comments:

Post a Comment