banner



How To Remove Key Value Pair From Hashmap In Java

Suppose you lot have a Map or Dictionaries like HashMap or Hashtable, which contains central-value pairs similar books and their prices, and you want to delete all books whose prices are greater than 40 USD, how practice you that in Java? This is ane of the most mutual scenarios while developing Java applications and many Java programmers, will say that they will iterate over Map and check each entry and then use theremove(Object fundamental) or remove(Object key, Object value) methods from java.util.Map to delete any mapping where the value is greater than 40 USD. Though the approach is right, the answer is incorrect.

Yes, we'll iterate over Map to bank check each value but we'll non apply the ii remove() methods from java.util.Map interface because they will throw ConcurrentModficationException when you lot phone call them to remove mapping during iteration.

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

The Iterator is a common interface that allows yous to go through each element of any Collection class including Map.

Though, since Map doesn't implement aCollection interface, yous just cannot direct become an iterator from Map, just you can always get a view of Map and and then get the iterator from those set similar,  set of keys by calling keySet() method.

It returns a set because of java.util.Map doesn't permit duplicate keys.  If you are not familiar with basic Drove classes in Java, like Listing, Set, and Map, I propose you first go through a comprehensive course in Java, likeThe Complete Java MasterClass on Udemy. It explains all those fundamentals quite well.

How to delete an entry from a HashMap during Iteration? Example

You tin also become a collection of values past calling the values() method considering values can repeat in Map, and prepare of entries by calling the entrySet()method. These Prepare and Drove are backed by the actual map, hence any modification you practice on this view will reverberate in the original map.

Apart from the navigation method likehasNext() and next(), Iterator also contains a remove() method which is used to remove the electric current element from the Collection y'all are iterating. This method should be used to delete whatsoever entry or key-value pair from the map during iteration.

Fifty-fifty though, java.util.Map interface provides a couple of overloaded versions of the remove() method like theremove(Object key) which tin can be used to remove a mapping by key and remove(Object key, Object value) to remove a fundamental-value pair, they cannot be used when you lot are iterating over the map using Iterator or enhanced for loop (remember Coffee 1.5 for-each loop is internally implemented using Iterator itself).

If you apply them to remove mapping your code will throw ConcurrentModfiicationException, even if y'all are running your code on a single thread surround.

Yep, the discussion concurrent has confused many Java programmers for years, who get scared of getting this exception in a multithreading surroundings, merely here concurrent is used in conjunction with iteration + any other operation which modifies the structure of Collection.

In curt, ever utilise Iterator's remove() method to remove a key-value pair from Map while iterating over it. Here are the exact steps to remove a key-value pair from java.util.Map

1) Become a Set of keys or Fix of entries by calling keySet() or entrySet() method of java.util.Map
two) Get the Iterator from the key set or entry set.
3) Iterate over cardinal set or entry set.
iv) Check each value, if information technology satisfies the criterion phone call iterator.remove() method

In one case y'all finish iteration, the mappings which satisfy the removal criterion should have been removed. Though, if yous desire to learn more about Iterator and in general the Collection framework, I suggest yous go throughJava Fundamentals: Collections past Richard Richard Warburton on Pluralsight. Information technology'south a specialized course on Collections and covers the topic in-depth.

Now, allow's run into a complete Java program to remove entries from Map.

Java Program to remove fundamental-value pairs while traversing a Map

In this programme, I accept a map of Java books and their prices, taken from Amazon.com. Basically, we accept 5 best Java books and their prices and our task is to remove all books whose price is college than 39 dollars. In order to do that, I'll iterate over Map and call Iterator.remove() method afterward checking the toll of the book.

I am using entrySet() for traversing Map considering information technology gives you entry, which contains both key and value. If you need both, then this is faster than traversing Map using a ready of keys, because you need to perform a lookup to get the value.

If the price of the book is higher than 39 USD so we remove the book by calling the iterator's remove() method. We become the cost past calling the getValue() method.

          import          java.util.HashMap;          import          java.util.Iterator;          import          java.util.Map;          import          java.util.Map.Entry;          import          coffee.util.Prepare;          /*  * Coffee Program to remove central value pair from Map while   * iteration.   */          public          class          Demo          {          public          static          void          master(String[] args)          throws          Exception          {          // create a Map to demonstrate example          Map<Cord, Double>          priceMap          =          new          HashMap<String, Double>();          // add together some mapping due east.g. popular Java books and their prices          priceMap.put("Effective Coffee", 41.79);     priceMap.put("Head Commencement Java", 29.02);     priceMap.put("Coffee Concurrency In Do", 30.67);     priceMap.put("Coffee SE 8 for Really Impatient", 31.99);     priceMap.put("Caput First Design Pattern", 39.05);          // let's remove all books which are greater than 39.00 USD from map          // go a set of entries          Set<Entry<String, Double>>          setOfEntries          =          priceMap.entrySet();          // get the iterator from entry set          Iterator<Entry<String, Double>>          iterator                      =          setOfEntries.iterator();          // iterate over map          while          (iterator.hasNext()) {          Entry<String, Double>          entry          =          iterator.side by side();          Double          value          =          entry.getValue();          if          (value.compareTo(Double          .valueOf(39.00))          >          0) {          System          .out.println("removeing : "          +          entry);          // priceMap.remove(entry.getKey()); // wrong - will throw          // ConcurrentModficationException          // priceMap.remove(entry.getKey(), entry.getValue()); // wrong - will          // throw mistake          iterator.remove();          // always use remove() method of iterator          }      }   }  }          Output          Removing          :          Head          First          Blueprint          Pattern          =39.05          Removing          :          Effective          Coffee          =41.79

Our lawmaking is likewise gratuitous from ConcurrentModificaitonException becuase nosotros are using Iterator's remove() method. If you lot uncomment the line which uses Map.remove() method then the code will throw ConcurrentMdofiicationException, as shown below:

Exception in thread "main" java.util.ConcurrentModificationException
at coffee.util.HashMap$HashIterator.nextNode(HashMap.java:1437)
at coffee.util.HashMap$EntryIterator.next(HashMap.java:1471)
at coffee.util.HashMap$EntryIterator.next(HashMap.java:1469)
at Demo.main(Demo.java:34)

Don't misfile why you are getting concurrent modification exceptions even if just i thread is modifying the collection. The concurrent here doesn't mean multi-threading but simultaneously performing two operations like iteration and removal.

That's all about how to remove a key-value pair from Map during traversal. Yous should ever utilize Iterator'southward remove() method to remove any mapping from the map while iterating over it to avoid any mistake. Use ofMap.remove() method is prohibited during traversal because it throws ConcurrentMdoficiationException.

Thank you for reading this article then far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback and then please drop a annotate.

P. S. - If yous are new to the Java globe and looking for a complimentary online preparation course to learn Java then y'all tin can also check out this Coffee Tutorial for Complete Beginners grade on Udemy. It's completely free and you just need a Udemy account to bring together this online course.

Source: https://javarevisited.blogspot.com/2017/08/how-to-remove-key-value-pair-from-map-iteration-java-example.html

0 Response to "How To Remove Key Value Pair From Hashmap In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel