How to make changes to a subset of items in a list

oldUsers is just a subset of allUsers, and all old users become active in the following list. The logic currently works, but I repeat allUsers only to get the oldUser handle each time before setting the active flag to false. Is there a way to pull the corresponding record and make changes (oldUsers and allUsers are of type Set<User>)

for (User oldUser : oldUsers) {
    for (User  user : allUsers) {
        if (user.getId().equals(oldUser.getId())) {
            user.setActive(false);
        }
    }
}
+3
source share
3 answers

oldUsers , setActive(false) allUsers, , .equals(. ) . :

Set<User> toInactivate = new HashSet<User>(allUsers);
toInactivate.retainAll(oldUsers);
for (User u : toInactivate)
    u.setActive(false);

(, ) - Map<Integer, User> .

for (int id : oldUsers.keySet())
    allUsers.get(id).setActive(false);
+5

oldUser allUsers , oldUser.
, hashcode , : allUsers.retainAll(oldUsers). , , allUser. allUser set, , ( ).

+1

Define User.equals () so that it compares getId () s and calls List.indexOf (user).

-2
source

Source: https://habr.com/ru/post/1765955/


All Articles