Saturday, November 15, 2014

Removing elements while iterating a Map in Java

Use an Iterator when removing an item from a Map Collection while iterating it so that it will not cause undefined behavior or the 'java.util.ConcurrentModificationException' exception.

To remove elements from a Map while iterating, you should use Iterator as shown below:

//set a reference to the map
Map<String,Person> groupPersonMap = .....

Iterator<Map.Entry<String,Person>> iter = groupPersonMap.entrySet().iterator();
while (iter.hasNext()) {
   Map.Entry<String,PersonObj> entry = iter.next();
   String groupId = entry.getKey();
   Person person = entry.getValue();
   if ("name filter here".equals(person.getName())) {
      // Remove the current element from the iterator and the map.
      iter.remove();
   }
}

Note that Iterator.remove is the only safe way to modify a collection during iteration. The behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Collection API
Map API

No comments:

Post a Comment