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();
}
}
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