-2

The following piece of code, while executed by a single thread, throws a ConcurrentModificationException on line 4:

Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
for (String key : map.keySet()) { // Here
    map.remove(key);
}

I couldn't find any Map.iterator() or Map.mapIterator() method on HashMap Javadoc. What should I do?

spongebob
  • 8,370
  • 15
  • 50
  • 83
  • 2
    Your question looks like [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you trying to do? For now it looks like you are trying to reinvent `map.crear()` method, or `map.keySet().clear()` or even `map.values().clear();`. – Pshemo Jun 20 '15 at 09:59
  • @Pshemo Having a much more complicated scenario, I preferred to write a [MCVE](http://stackoverflow.com/help/mcve) from scratch here. – spongebob Jun 20 '15 at 12:54

1 Answers1

2

As you guessed, you need an iterator for removing items during iteration. The way to do it with a Map is to iterate the entrySet() (or, alternatively, the keySet(), if you only need to evaluate the key):

Iterator<Map.Entry<String, String>> entryIter = map.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String, String> entry = iter.next();
    iter.remove(); // Probably guard this by some condition?
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350