How To Take Fundamental Value Twain From Map During Iteration - Event Tutorial
Wednesday, August 8, 2018
Add Comment
Suppose you lot own got a Map e.g. HashMap or Hashtable, which contains primal value pairs e.g. books as well as their prices, as well as you lot desire to take all books whose prices are greater than xl USD, How practise you lot that inward Java? Many Java programmer, volition say that they volition iterate over Map as well as banking firm gibe each entry as well as and so purpose remove(Object key) or remove(Object key, Object value) methods from java.util.Map to take whatsoever mapping where the value is greater than xl USD. Though the approach is right, the respond is wrong. Yes, we'll iterate over Map to banking firm gibe each value but we'll non purpose the 2 remove() methods from java.util.Map interface because they volition throw ConcurrentModficationException, when you lot telephone vociferation upward them to take mapping during iteration. Instead, we'll purpose the Iterator.remove() method to take whatsoever primal value pair, where the value is greater than xl USD.
The Iterator is a mutual interface which allows you lot to become through each chemical gene of whatsoever Collection course of teaching including Map. Though, since Map doesn't implement Collection interface, you lot but cannot straight larn an iterator from Map, but you lot tin ever larn a persuasion of Map as well as and so larn the iterator from those prepare e.g. prepare of keys yesteryear calling keySet() method. It returns prepare because of java.util.Map doesn't allow duplicate keys. You tin too larn a collection of values yesteryear calling values() method because values tin repeat inward Map, as well as prepare of entries yesteryear calling the entrySet()method.
These Set as well as Collection are backed yesteryear the actual map, so whatsoever change you lot practise on this persuasion volition reverberate inward the master map. Apart from navigation method e.g. hasNext() as well as next(), Iterator too contains a remove() method which is used to take the electrical flow element from the Collection you lot are iterating. This method should live on used to delete whatsoever entry or primal value pair from the map during iteration.
Even though, java.util.Map interface provides a dyad of overloaded version of remove() method e.g. remove(Object key) which tin live on used to take a mapping yesteryear primal as well as remove(Object key, Object value) to take a primal value pair, they cannot live on used when you lot are iterating over map using Iterator or enhanced for loop (remember Java 1.5 for loop is internally implemented using Iterator itself).
If you lot purpose them to take mapping your code volition throw ConcurrentModfiicationException, fifty-fifty if you lot are running your code on unmarried thread environment. Yes, the discussion concurrent has confused many Java programmer from years, who larn scared of getting this exception inward a multithreading environment, but hither concurrent is used inward conjunction amongst iteration + whatsoever other functioning which modifies the construction of Collection.
In short, ever purpose Iterator's remove() method to take a primal value pair from Map spell iterating over it. Here are exact steps to take a primal value pair from java.util.Map
1) Get a Set of keys or Set of entries yesteryear calling keySet() or entrySet() method of java.util.Map
2) Get the Iterator from primal prepare or entry set.
3) Iterate over primal prepare or entry set.
4) Check each value, if it satisfies measure telephone vociferation upward iterator.remove() method
Once you lot destination iteration, the mappings which satisfy removal measure should own got been removed. Now, let's encounter a consummate Java programme to take entries from Map.
I am using entrySet() for traversing Map because it gives you lot entry, which contains both primal as well as value. If you lot involve both, as well as so this is faster than traversing Map using a prepare of keys, because you lot involve to perform a lookup to larn the value.
If the toll of the majority is higher than 39 USD as well as so nosotros take the majority yesteryear calling the iterator's remove() method. We larn the toll yesteryear calling the getValue() method.
From the output, you lot tin encounter that both Effective Java as well as Head First Design Patterns are removed because their toll is higher than 39 USD but Map yet contains other Java books e.g. Head First Java, Java Concurrency inward Practice, as well as Java SE 8 for Really Impatient.The Iterator is a mutual interface which allows you lot to become through each chemical gene of whatsoever Collection course of teaching including Map. Though, since Map doesn't implement Collection interface, you lot but cannot straight larn an iterator from Map, but you lot tin ever larn a persuasion of Map as well as and so larn the iterator from those prepare e.g. prepare of keys yesteryear calling keySet() method. It returns prepare because of java.util.Map doesn't allow duplicate keys. You tin too larn a collection of values yesteryear calling values() method because values tin repeat inward Map, as well as prepare of entries yesteryear calling the entrySet()method.
These Set as well as Collection are backed yesteryear the actual map, so whatsoever change you lot practise on this persuasion volition reverberate inward the master map. Apart from navigation method e.g. hasNext() as well as next(), Iterator too contains a remove() method which is used to take the electrical flow element from the Collection you lot are iterating. This method should live on used to delete whatsoever entry or primal value pair from the map during iteration.
Even though, java.util.Map interface provides a dyad of overloaded version of remove() method e.g. remove(Object key) which tin live on used to take a mapping yesteryear primal as well as remove(Object key, Object value) to take a primal value pair, they cannot live on used when you lot are iterating over map using Iterator or enhanced for loop (remember Java 1.5 for loop is internally implemented using Iterator itself).
If you lot purpose them to take mapping your code volition throw ConcurrentModfiicationException, fifty-fifty if you lot are running your code on unmarried thread environment. Yes, the discussion concurrent has confused many Java programmer from years, who larn scared of getting this exception inward a multithreading environment, but hither concurrent is used inward conjunction amongst iteration + whatsoever other functioning which modifies the construction of Collection.
In short, ever purpose Iterator's remove() method to take a primal value pair from Map spell iterating over it. Here are exact steps to take a primal value pair from java.util.Map
1) Get a Set of keys or Set of entries yesteryear calling keySet() or entrySet() method of java.util.Map
2) Get the Iterator from primal prepare or entry set.
3) Iterate over primal prepare or entry set.
4) Check each value, if it satisfies measure telephone vociferation upward iterator.remove() method
Once you lot destination iteration, the mappings which satisfy removal measure should own got been removed. Now, let's encounter a consummate Java programme to take entries from Map.
Java Program to take primal value pairs spell traversing a Map
In this program, I own got a map of Java books as well as their prices, taken from Amazon.com. Basically, nosotros own got five best Java books as well as their prices as well as our chore is to take all books whose toll is higher than 39 dollars. In gild to practise that, I'll iterate over Map as well as telephone vociferation upward Iterator.remove() method afterward checking the toll of the book.I am using entrySet() for traversing Map because it gives you lot entry, which contains both primal as well as value. If you lot involve both, as well as so this is faster than traversing Map using a prepare of keys, because you lot involve to perform a lookup to larn the value.
If the toll of the majority is higher than 39 USD as well as so nosotros take the majority yesteryear calling the iterator's remove() method. We larn the toll yesteryear calling the getValue() method.
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /* * Java Program to take primal value pair from Map spell * iteration. */ public class Demo { public static void main(String[] args) throws Exception { // practise a Map to demonstrate example Map<String, Double> priceMap = new HashMap<String, Double>(); // add together about mapping e.g. pop Java books as well as their prices priceMap.put("Effective Java", 41.79); priceMap.put("Head First Java", 29.02); priceMap.put("Java Concurrency In Practice", 30.67); priceMap.put("Java SE 8 for Really Impatient", 31.99); priceMap.put("Head First Design Pattern", 39.05); // let's take all books which are greater than 39.00 USD from map // larn a prepare of entries Set<Entry<String, Double>> setOfEntries = priceMap.entrySet(); // larn the iterator from entry set Iterator<Entry<String, Double>> iterator = setOfEntries.iterator(); // iterate over map while (iterator.hasNext()) { Entry<String, Double> entry = iterator.next(); Double value = entry.getValue(); if (value.compareTo(Double.valueOf(39.00)) > 0) { System.out.println("removeing : " + entry); // priceMap.remove(entry.getKey()); // incorrect - volition throw // ConcurrentModficationException // priceMap.remove(entry.getKey(), entry.getValue()); // incorrect - will // throw error iterator.remove(); // ever purpose remove() method of iterator } } } } Output Removing: Head First Design Pattern=39.05 Removing: Effective Java=41.79
Our code is too costless from ConcurrentModificaitonException becuase nosotros are using Iterator's remove() method. If you lot uncomment the business which uses Map.remove() method as well as so the code volition throw ConcurrentMdofiicationException, equally shwon below:
Exception inward thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437)
at java.util.HashMap$EntryIterator.next(HashMap.java:1471)
at java.util.HashMap$EntryIterator.next(HashMap.java:1469)
at Demo.main(Demo.java:34)
Don't confuse why you lot are getting concurrent change exception fifty-fifty if but 1 thread is modifying the collection. The concurrent hither doesn't hateful multi-threading but simultaneously performing 2 operations e.g. iteration as well as removal.
That's all almost how to take a primal value pair from Map during traversal. You should ever purpose Iterator's remove() method to take whatsoever mapping from the map spell iterating over it to avoid whatsoever error. Use of Map.remove() method is prohibited during traversal because it throws ConcurrentMdoficiationException.
Further Learning
The Complete Java MasterClass
tutorial)
How to variety an ArrayList inward ascending as well as descending gild inward Java? (tutorial)
Difference betwixt ArrayList as well as HashSet inward Java? (answer)
The divergence betwixt TreeMap as well as TreeSet inward Java? (answer)
The divergence betwixt HashMap as well as ConcurrentHashMap inward Java? (answer)
The divergence betwixt HashMap as well as LinkedHashMap inward Java? (answer)
The divergence betwixt Hashtable as well as HashMap inward Java? (answer)
The divergence betwixt HashSet as well as TreeSet inward Java? (answer)
The divergence betwixt ArrayList as well as LinkedList inward Java? (answer)
The divergence betwixt Vector as well as ArrayList inward Java? (answer)
Difference betwixt EnumMap as well as HashMap inward Java
The divergence betwixt TreeMap as well as TreeSet inward Java? (answer)
The divergence betwixt HashMap as well as ConcurrentHashMap inward Java? (answer)
The divergence betwixt HashMap as well as LinkedHashMap inward Java? (answer)
The divergence betwixt Hashtable as well as HashMap inward Java? (answer)
The divergence betwixt HashSet as well as TreeSet inward Java? (answer)
The divergence betwixt ArrayList as well as LinkedList inward Java? (answer)
The divergence betwixt Vector as well as ArrayList inward Java? (answer)
Difference betwixt EnumMap as well as HashMap inward Java
Thanks for reading this article so far. If you lot similar this article as well as so delight part amongst your friends as well as colleagues. If you lot own got whatsoever enquiry or feedback as well as so delight drib a comment.
0 Response to "How To Take Fundamental Value Twain From Map During Iteration - Event Tutorial"
Post a Comment