180

I am having HashMap called testMap which contains String, String.

HashMap<String, String> testMap = new HashMap<String, String>();

When iterating the map, if value is match with specified string, I need to remove the key from map.

i.e.

for(Map.Entry<String, String> entry : testMap.entrySet()) {
  if(entry.getValue().equalsIgnoreCase("Sample")) {
    testMap.remove(entry.getKey());
  }
}

testMap contains "Sample" but I am unable to remove the key from HashMap.
Instead getting error :

"Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
    at java.util.HashMap$EntryIterator.next(Unknown Source)
    at java.util.HashMap$EntryIterator.next(Unknown Source)"
Adam Horvath
  • 1,249
  • 1
  • 10
  • 25
ssbecse
  • 1,895
  • 3
  • 13
  • 7
  • 1
    Please always copy/paste code snippets, rather than type 'something like' the code used. The original code shown could not throw a run-time exception, since it was uncompilable. – Andrew Thompson May 23 '11 at 04:19
  • 1
    Another option, while cludgy, is to create a list of the objects you want to remove while you're iterating. Then you can create another loop after your initial loop that iterates over that list and removes them from the hashmap. – eipark May 22 '13 at 17:42

2 Answers2

378

Try:

Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if("Sample".equalsIgnoreCase(entry.getValue())){
        iter.remove();
    }
}

With Java 1.8 and onwards you can do the above in just one line:

testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));
Tom
  • 43,583
  • 4
  • 41
  • 61
  • 7
    What if you want to remove an item that isn't the one that your iterator is on? – Dave Aug 20 '12 at 20:10
  • 9
    @HDave It's possible using a method like `Map.remove (Object key)`, but should not be done during iteration. If you use any remove method other than `Iterator.remove()` during iteration, the results of the iteration are undefined. Either wait until the iterator is "on" the entry you want to remove and use `Iterator.remove()`, or do it outside of (before/after) the iteration loop. If it's the latter, make sure to get a new iterator from the entry set before doing any iteration on the map, as any previous iterator will yield undefined results. –  Oct 02 '12 at 06:34
  • 2
    Or you could use a `for` loop with similar semantics, see http://stackoverflow.com/a/1884916/32453 – rogerdpack Aug 17 '15 at 20:14
  • 1
    I had this problem many years ago before Java 8 and I used ConcurrentHashMap instead of HashMap. – Mehdi Apr 17 '18 at 23:43
16

Use Iterator.remove().

Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94