Can you lot take a primal piece iterating over HashMap inwards Java? This is ane of the interesting interview questions every bit good every bit a mutual work Java developer confront piece writing code using HashMap. Some programmer volition nation No, you lot cannot take elements from HashMap piece iterating over it. This volition neglect fast together with throw concurrent alteration exception. They are right only non completely. It's truthful that the iterator of HashMap is a fail-fast iterator only you lot tin orbit the sack however take elements from HashMap piece iterating past times using Iterator's remove() method. This is the same technique which nosotros convey used inwards past times to take elements piece iterating over a List inwards Java. The primal hither is non to purpose the remove() method from Map or List interface to avoid java.util.ConcurrentModfiicationException inwards Java.
The ConcurrentModificationException comes when you lot use Map.remove(Object key) to take a key. Remember, when you lot take a key, the mapping itself is removed i.e. both primal together with value objects are removed from Map together with 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 upward past times calling iterator() method of the Set interface.
3. Iterate over Map using this Iterator together with piece loop
4. Remove an entry from a map based on matching primal from laid upward e.g. you lot tin orbit the sack compare the primal from Set amongst the detail you lot desire to take past times using Iterator.remove() method
Here is an instance to remove elements from HashMap piece iterating. In this example, I convey a Map of diverse Java together with Spring certifications together with their toll e.g OCAJP (1Z0-808) toll approximately 248 the States Dollars, same is for OCPJP 8 (1Z0-809), piece Spring certifications provided past times Pivotal e.g. Spring Professional Certification Exam together with Spring Web Application Developer Exam toll approximately 200 USD each (see here).
While Iterating over Map, I compare primal amongst the OCMJEA (Oracle Certified Master Java Enterprise Architect) together with if the primal matches so I take it from the Map. Here, I convey used the remove() method of HashMap, therefore this programme volition throw ConcurrentModfiicationException.
You tin orbit the sack run into the Iterator of HashMap throws java.util.ConcurrentModificationException every bit shortly every bit you lot endeavour to take an entry piece iterating over Map because the iterator is fail-fast. If this had been a ConcurentHashMap so it won't throw the ConcurrentModficationExcetpion. Now, let's run into the right means to take an entry from HashMap piece iterating over it.
Here is the right means to take a primal or an entry from HashMap inwards Java piece iterating over it. This code uses Iterator together with its remove() method to delete a primal from HashMap. When you lot take a key, the value too gets removed from HashMap i.e. it's a shortcut to take an entry from HashMap inwards Java.
From the output you lot tin orbit the sack run into that the entry associated amongst "OCMJEA 1Z0-807" primal is removed the Map, at that spot were four entries earlier removal together with straightaway at that spot are exclusively iii entries remaining. Also, at that spot is no ConcurrentModificationException occurs.
Java 8 Facts
In Java 8 you lot tin orbit the sack 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 near novel methods added into existing interfaces inwards JDK 8.
That's all near how to take a primal or an entry/mapping piece iterating over HashMap inwards Java. You cannot take an entry piece looping over Map only you lot tin orbit the sack take a primal or value piece iterating over it. Since Iterator of HashMap is fail-fast it volition throw ConcurrentModificationException if you lot endeavour to take entry using Map.remove(Object key) method, the right means to take an entry from the HashMap past times using Iterator's remove() method.
Further Reading
Java Fundamentals: Collections
From Collections to Streams inwards Java 8 Using Lambda Expressions
What's New inwards Java 8
25 Java Collection Interview Questions
How HashMap plant inwards Java
How ConcurrentHashMap plant inwards Java
Java Programming Interview Exposed past times Makhem
Thanks for reading this article this far. If you lot similar this tutorial so delight portion amongst your friends together with colleagues. IF you lot convey whatever enquiry or feedback so delight driblet a comment.
The ConcurrentModificationException comes when you lot use Map.remove(Object key) to take a key. Remember, when you lot take a key, the mapping itself is removed i.e. both primal together with value objects are removed from Map together with 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 upward past times calling iterator() method of the Set interface.
3. Iterate over Map using this Iterator together with piece loop
4. Remove an entry from a map based on matching primal from laid upward e.g. you lot tin orbit the sack compare the primal from Set amongst the detail you lot desire to take past times using Iterator.remove() method
Here is an instance to remove elements from HashMap piece iterating. In this example, I convey a Map of diverse Java together with Spring certifications together with their toll e.g OCAJP (1Z0-808) toll approximately 248 the States Dollars, same is for OCPJP 8 (1Z0-809), piece Spring certifications provided past times Pivotal e.g. Spring Professional Certification Exam together with Spring Web Application Developer Exam toll approximately 200 USD each (see here).
While Iterating over Map, I compare primal amongst the OCMJEA (Oracle Certified Master Java Enterprise Architect) together with if the primal matches so I take it from the Map. Here, I convey used the remove() method of HashMap, therefore 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 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 inwards 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 orbit the sack run into the Iterator of HashMap throws java.util.ConcurrentModificationException every bit shortly every bit you lot endeavour to take an entry piece iterating over Map because the iterator is fail-fast. If this had been a ConcurentHashMap so it won't throw the ConcurrentModficationExcetpion. Now, let's run into the right means to take an entry from HashMap piece iterating over it.
Right means to Remove a primal from HashMap piece Iterating inwards Java
Here is the right means to take a primal or an entry from HashMap inwards Java piece iterating over it. This code uses Iterator together with its remove() method to delete a primal from HashMap. When you lot take a key, the value too gets removed from HashMap i.e. it's a shortcut to take an entry from HashMap inwards 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 primal from HashMap piece iterating Iterator<String> iterator = certificationCost.keySet().iterator(); while(iterator.hasNext()){ String certification = iterator.next(); if(certification.contains("OCMJEA")){ iterator.remove(); } } // Map - afterward 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 you lot tin orbit the sack run into that the entry associated amongst "OCMJEA 1Z0-807" primal is removed the Map, at that spot were four entries earlier removal together with straightaway at that spot are exclusively iii entries remaining. Also, at that spot is no ConcurrentModificationException occurs.
Java 8 Facts
In Java 8 you lot tin orbit the sack 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 near novel methods added into existing interfaces inwards JDK 8.
That's all near how to take a primal or an entry/mapping piece iterating over HashMap inwards Java. You cannot take an entry piece looping over Map only you lot tin orbit the sack take a primal or value piece iterating over it. Since Iterator of HashMap is fail-fast it volition throw ConcurrentModificationException if you lot endeavour to take entry using Map.remove(Object key) method, the right means to take an entry from the HashMap past times using Iterator's remove() method.
Further Reading
Java Fundamentals: Collections
From Collections to Streams inwards Java 8 Using Lambda Expressions
What's New inwards Java 8
25 Java Collection Interview Questions
How HashMap plant inwards Java
How ConcurrentHashMap plant inwards Java
Java Programming Interview Exposed past times Makhem
Thanks for reading this article this far. If you lot similar this tutorial so delight portion amongst your friends together with colleagues. IF you lot convey whatever enquiry or feedback so delight driblet a comment.

0 Response to "How to Remove Entry (key/value) from HashMap spell Iterating? Example Tutorial"
Posting Komentar