我认为在尝试从forEach()
循环中的集合中删除一个对象时,我犯了一个小错误。remove()
不移除对象,有人能指出问题的所在吗?谢谢!
Set<RoleExtEntity> roleExtEntitySet = roleEntity.getExt(); //set size = 3
Map<String, RoleExtEntity> roleExtEntityMap =
new HashMap<>(roleExtEntitySet.size());
roleExtEntitySet.stream().forEach(roleExtEntity -> {
if (role.getName() == null && roleExtEntity.getKey().equals("name")) {
//this line doesn't work; set size should be 2 but it's still 3
roleExtEntitySet.remove(roleExtEntity);
} else {
roleExtEntityMap.put(roleExtEntity.getKey(), roleExtEntity);
}
});
发布于 2021-09-29 01:38:17
任何人都能指出问题的所在
在没有看到代码的情况下,我猜想这是因为您没有正确地覆盖equals
和/或hashCode
,而且/或您已经修改了roleExtEntity
,因为它被放入到映射中,从而影响了hashCode
。
不管怎么说,如果这个remove
确实工作了,您就会冒出一个ConcurrentModificationException
的风险,因为您正在从正在迭代的集合中移除。
相反,您可以使用显式Iterator
来实现这一点,它允许您使用remove()
for (Iterator<RoleExtEntity> it = roleExtEntitySet.iterator(); it.hasNext();) {
RoleExtEntity roleExtEntity = it.next();
if (...) {
it.remove();
} else {
// ...
}
}
另一种选择可以是将forEach
分解为执行移除操作和执行放置操作的操作:
if (role.getName() == null) { // Since role appears to be unchanged in the loop
roleExtEntitySet.removeIf(roleExtEntity -> roleExtEntity.getKey().equals("name"));
}
Map<String, RoleExtEntity> roleExtEntityMap =
roleExtEntitySet.stream().collect(
Collectors.toMap(RoleExtEntity::getKey, r -> r));
https://stackoverflow.com/questions/69373781
复制