How To Delete A Fundamental Value Duo From A Hashmap During Iteration Inwards Coffee - Example Tutorial

Suppose you lot convey a Map or Dictionaries similar HashMap or Hashtable, which contains key-value pairs similar books too their prices, too you lot desire to delete all books whose prices are greater than twoscore USD, how exercise you lot that inwards Java? This is 1 of the most mutual scenarios spell developing Java application too many Java programmer, volition state that they volition iterate over Map too cheque each entry too so operate the remove(Object key) or remove(Object key, Object value) methods from java.util.Map to delete whatever mapping where the value is greater than twoscore USD. Though the approach is right, the reply is wrong.

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

Instead, we'll operate the Iterator.remove() method to delete whatever key-value pair, where the value is greater than twoscore USD.

The Iterator is a mutual interface which allows you lot to acquire through each chemical constituent of whatever Collection course of teaching including Map.

Though, since Map doesn't implement Collection interface, you lot simply cannot straight acquire an iterator from Map, but you lot tin ever acquire a persuasion of Map too so acquire the iterator from those fix e.g. fix of keys past times calling keySet() method.

It returns fix because of java.util.Map doesn't allow duplicate keys.  If you lot are non familiar alongside basic Collection classes inwards Java similar List, Set, too Map, I propose you lot to start acquire through a comprehensive course of teaching 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 likewise acquire a collection of values past times calling values() method because values tin repeat inwards Map, too fix of entries past times calling the entrySet()method. These Set too Collection are backed past times the actual map, thence whatever alteration you lot exercise on this persuasion volition reverberate inwards the master copy map.

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

Even though, java.util.Map interface provides a span of overloaded version of remove() method e.g. remove(Object key) which tin last used to take away a mapping past times key too remove(Object key, Object value) to take away a key-value pair, they cannot last 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 operate 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 alongside iteration + whatever other functioning which modifies the construction of Collection.

In short, always operate 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 fix or entry set.
3) Iterate over key fix or entry set.
4) Check each value, if it satisfies touchstone telephone band iterator.remove() method

Once you lot destination iteration, the mappings which satisfy removal touchstone should convey been removed. Though, if you lot desire to larn to a greater extent than nearly Iterator too inwards full general Collection framework, I propose you lot acquire through traversing Map using a fix of keys, because you lot involve to perform a lookup to acquire the value.

If the cost of the majority is higher than 39 USD so nosotros take away the majority past times calling the iterator's remove() method. We acquire the cost 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 {      // exercise a Map to demonstrate example     Map<String, Double> priceMap = new HashMap<String, Double>();      // add together simply about mapping e.g. pop Java books too 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 fix 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 operate remove() method of iterator       }      }   }  } Output Removing: Head First Design Pattern=39.05 Removing: Effective Java=41.79


From the output, you lot tin run into that both Effective Java too Head First Design Patterns are removed because their cost is higher than 39 USD but Map nonetheless contains other Java books e.g. Head First Java, Java Concurrency inwards Practice, too 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 business which uses Map.remove() method so the code volition throw ConcurrentMdofiicationException, equally 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 alteration exception fifty-fifty if simply 1 thread is modifying the collection. The concurrent hither doesn't hateful multi-threading but simultaneously performing 2 operations e.g. iteration too removal.


That's all nearly how to take away a key-value pair from Map during traversal. You should ever operate Iterator's remove() method to take away whatever mapping from the map spell iterating over it to avoid whatever error. Use of  Map.remove() method is prohibited during traversal because it throws ConcurrentMdoficiationException.

Further Learning
The Complete Java MasterClass
tutorial)
How to kind an ArrayList inwards ascending too descending gild inwards Java? (tutorial)
Difference betwixt ArrayList too HashSet inwards Java? (answer)
The departure betwixt TreeMap too TreeSet inwards Java? (answer)
The departure betwixt HashMap too ConcurrentHashMap inwards Java? (answer)
The departure betwixt HashMap too LinkedHashMap inwards Java? (answer)
The departure betwixt Hashtable too HashMap inwards Java? (answer)
The departure betwixt HashSet too TreeSet inwards Java? (answer)
The departure betwixt ArrayList too LinkedList inwards Java? (answer)
The departure betwixt Vector too ArrayList inwards Java? (answer)
Difference betwixt EnumMap too HashMap inwards Java

Thanks for reading this article so far. If you lot similar this article so delight portion alongside your friends too colleagues. If you lot convey whatever interrogation or feedback so delight drib a comment.

Belum ada Komentar untuk "How To Delete A Fundamental Value Duo From A Hashmap During Iteration Inwards Coffee - Example Tutorial"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel