EDIT its worked
group.getUsers().forEach(user -> {
user.removeGroup(group);
privilegeRepository.findAll().stream().
filter(privilege -> privilege.getName().startsWith(slugname.toUpperCase()))
.forEach(privilege -> {
user.removePrivilege(privilege);
privilegeRepository.delete(privilege);
});
});
I have nested for-loops and I want to replace that for-loops with a forEach:
for (User user : group.getUsers()) {
user.removeGroup(group);
for(Privilege privilege : user.getPrivileges()){
if (privilege.getName().startsWith(slugname.toUpperCase())){
user.removePrivilege(privilege);
privilegeRepository.delete(privilege);
}
}
}
to
group.getUsers().forEach(user -> {
user.removeGroup(group);
user.getPrivileges().stream().filter(privilege -> privilege.getName().startsWith(slugname.toUpperCase()))
.forEach(privilege -> {
user.removePrivilege(privilege);
privilegeRepository.delete(privilege);
});
});
And it throws a exception:
java.util.ConcurrentModificationException
user.getPrivileges()vsprivilegeRepository.findAll(): doesn't look like the two are doing the same thingremove()on to get the privilege removed from the user's privileges.user.removePrivilegewhile iterating overuser.getPrivileges. You need to make a snapshot copy to iterate over.java.util.ConcurrentModificationExceptionin the first example (with the nested for-loops). I thinkuser.removePrivilege(privilege);still can make modification on the collection that you are iterating in the same time.