How to make modifications on a subset of elements in a list
oldUsers is just a subset of allUsers and all oldUsers are made in-active in the following list. The logic currently works, but I am iterating allUsers just to get the handle of oldUser every time, before 开发者_C百科I set the active flag to false. Is there a way to pull the appropriate record and make my modifications (oldUsers and allUsers is of type Set<User>
)
for (User oldUser : oldUsers) {
for (User user : allUsers) {
if (user.getId().equals(oldUser.getId())) {
user.setActive(false);
}
}
}
If oldUsers
contains copies or fresh instances of users, and you simply want to setActive(false)
on those users in allUsers
that have a matching id, then I suggest you override the .equals (and .hash) methods of User based on the user id. You could then do like this:
Set<User> toInactivate = new HashSet<User>(allUsers);
toInactivate.retainAll(oldUsers);
for (User u : toInactivate)
u.setActive(false);
Another way (perhaps even more elegant) would be to store the users in a Map<Integer, User>
mapping user ids to users. You could then simply do
for (int id : oldUsers.keySet())
allUsers.get(id).setActive(false);
if objects in oldUser and in allUsers are the same instances, than you just change oldUser.
if not, you define hashcode and equals, and than do: allUsers.retainAll(oldUsers)
. Thus you will get interception of these two Sets, which consist of allUser instances. allUser set, however, will be changed (it'll shrink).
Define User.equals() such that it compares getId()s, and call List.indexOf(user).
精彩评论