0

Assuming I know the key, is it possible to remove it when iterating over

for (ExampleClass e : map.values()) {
    if (condition) {
        map.remove(key);
    }
}

I have found a related question (iterating over and removing from a map), but it assumes we are iterating over the key set. Does the same apply to the value set?

Community
  • 1
  • 1
kacpr
  • 440
  • 1
  • 8
  • 28

1 Answers1

4

From the HashMap javadoc:

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

So you can't use map.remove(key).

From the javadoc for HashMap#values():

The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations.

So you can use Iterator#remove() to remove entries from the value set.

awksp
  • 11,764
  • 4
  • 37
  • 44