How To Delete A Telephone Substitution Value Couplet From A Hashmap During Iteration Inwards Coffee - Illustration Tutorial

Advertisement

Masukkan script iklan 970x90px

How To Delete A Telephone Substitution Value Couplet From A Hashmap During Iteration Inwards Coffee - Illustration Tutorial

Sabtu, 28 Maret 2020

Suppose you lot convey a Map or Dictionaries similar HashMap or Hashtable, which contains key-value pairs similar books in addition to their prices, in addition to you lot desire to delete all books whose prices are greater than forty USD, how practice you lot that inwards Java? This is i of the most mutual scenarios spell developing Java application in addition to many Java programmer, volition nation that they volition iterate over Map in addition to banking concern stand upward for each entry in addition to so role the remove(Object key) or remove(Object key, Object value) methods from java.util.Map to delete whatsoever mapping where the value is greater than forty USD. Though the approach is right, the reply is wrong.

Yes, we'll iterate over Map to banking concern stand upward for each value but we'll non role the 2 remove() methods from java.util.Map interface because they volition throw ConcurrentModficationException when you lot telephone telephone them to take away mapping during iteration.

Instead, we'll role the Iterator.remove() method to delete whatsoever key-value pair, where the value is greater than forty USD.

The Iterator is a mutual interface which allows you lot to acquire through each chemical ingredient of whatsoever Collection bird including Map.

Though, since Map doesn't implement Collection interface, you lot only cannot straight acquire an iterator from Map, but you lot tin post away ever acquire a persuasion of Map in addition to so acquire the iterator from those gear upward e.g. gear upward of keys past times calling keySet() method.

It returns gear upward because of java.util.Map doesn't allow duplicate keys.  If you lot are non familiar amongst basic Collection classes inwards Java similar List, Set, in addition to Map, I advise you lot to start acquire through a comprehensive course of pedagogy inwards Java like The Complete Java MasterClass on Udemy. It explains all those fundamentals quite well.




How to delete an entry from a HashMap during Iteration

You tin post away likewise acquire a collection of values past times calling values() method because values tin post away repeat inwards Map, in addition to gear upward of entries past times calling the entrySet()method. These Set in addition to Collection are backed past times the actual map, thence whatsoever change you lot practice on this persuasion volition reverberate inwards the master copy map.

Apart from navigation method e.g. hasNext() in addition to next(), Iterator likewise contains a remove() method which is used to take away the electrical flow element from the Collection you lot are iterating. This method should move used to delete whatsoever entry or key-value pair from the map during iteration.

Even though, java.util.Map interface provides a yoke of overloaded version of remove() method e.g. remove(Object key) which tin post away move used to take away a mapping past times key in addition to remove(Object key, Object value) to take away a key-value pair, they cannot move used when you lot are iterating over map using Iterator or enhanced for loop (remember Java 1.5 for each loop is internally implemented using Iterator itself).

If you lot role them to take away 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 acquire scared of getting this exception inwards a multithreading environment, but hither concurrent is used inwards conjunction amongst iteration + whatsoever other functioning which modifies the construction of Collection.

In short, always role Iterator's remove() method to take away a key-value pair from Map spell iterating over it. Here are exact steps to take away a key-value pair from java.util.Map

1) Get a Set of keys or Set of entries past times calling keySet() or entrySet() method of java.util.Map
2) Get the Iterator from the key gear upward or entry set.
3) Iterate over key gear upward or entry set.
4) Check each value, if it satisfies measure telephone telephone iterator.remove() method

Once you lot goal iteration, the mappings which satisfy removal measure should convey been removed. Though, if you lot desire to larn to a greater extent than virtually Iterator in addition to inwards full general Collection framework, I advise you lot acquire through traversing Map using a gear upward of keys, because you lot involve to perform a lookup to acquire the value.

If the toll of the mass is higher than 39 USD so nosotros take away the mass past times calling the iterator's remove() method. We acquire the toll past times 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 away key value pair from Map spell   * iteration.   */ public class Demo {    public static void main(String[] args) throws Exception {      // practice a Map to demonstrate example     Map<String, Double> priceMap = new HashMap<String, Double>();      // add together to a greater extent than or less mapping e.g. pop Java books in addition to 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 away all books which are greater than 39.00 USD from map     // acquire a gear upward of entries     Set<Entry<String, Double>> setOfEntries = priceMap.entrySet();      // acquire 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 role remove() method of iterator       }      }   }  } Output Removing: Head First Design Pattern=39.05 Removing: Effective Java=41.79


From the output, you lot tin post away come across that both Effective Java in addition to Head First Design Patterns are removed because their toll is higher than 39 USD but Map however contains other Java books e.g. Head First Java, Java Concurrency inwards Practice, in addition to Java SE 8 for Really Impatient.

 Suppose you lot convey a Map or Dictionaries similar HashMap or Hashtable How to delete a key value pair from a HashMap during Iteration inwards Java - Example tutorial


Our code is likewise gratis from ConcurrentModificaitonException becuase nosotros are using Iterator's remove() method. If you lot uncomment the job which uses Map.remove() method so the code volition throw ConcurrentMdofiicationException, every bit shwon below:

Exception inwards 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 only i thread is modifying the collection. The concurrent hither doesn't hateful multi-threading but simultaneously performing 2 operations e.g. iteration in addition to removal.


That's all virtually how to take away a key-value pair from Map during traversal. You should ever role Iterator's remove() method to take away 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 form an ArrayList inwards ascending in addition to descending guild inwards Java? (tutorial)
Difference betwixt ArrayList in addition to HashSet inwards Java? (answer)
The departure betwixt TreeMap in addition to TreeSet inwards Java? (answer)
The departure betwixt HashMap in addition to ConcurrentHashMap inwards Java? (answer)
The departure betwixt HashMap in addition to LinkedHashMap inwards Java? (answer)
The departure betwixt Hashtable in addition to HashMap inwards Java? (answer)
The departure betwixt HashSet in addition to TreeSet inwards Java? (answer)
The departure betwixt ArrayList in addition to LinkedList inwards Java? (answer)
The departure betwixt Vector in addition to ArrayList inwards Java? (answer)
Difference betwixt EnumMap in addition to HashMap inwards Java

Thanks for reading this article so far. If you lot similar this article so delight percentage amongst your friends in addition to colleagues. If you lot convey whatsoever interrogation or feedback so delight driblet a comment.