Update a list from another list
Posted
by Langali
on Stack Overflow
See other posts from Stack Overflow
or by Langali
Published on 2010-03-12T20:46:21Z
Indexed on
2010/03/12
20:47 UTC
Read the original article
Hit count: 797
I have a list of users in local store that I need to update from a remote list of users every once in a while. Basically:
- If a remote user already exists locally, update its fields.
- If a remote user doesn't already exist locally, add the user.
- If a local user doesn't appear in the remote list, deactivate or delete.
- If a local user also appears in the remote list, update its fields.
Just a simple case of syncing the local list. Is there a better way to do this in pure Java than the following? I feel gross looking at my own code.
public class User {
Integer id;
String email;
boolean active;
//Getters and Setters.......
public User(Integer id, String email, boolean active) {
this.id = id;
this.email = email;
this.active = active;
}
@Override
public boolean equals(Object other) {
boolean result = false;
if (other instanceof User) {
User that = (User) other;
result = (this.getId() == that.getId());
}
return result;
}
}
public static void main(String[] args) {
//From 3rd party
List<User> remoteUsers = getRemoteUsers();
//From Local store
List<User> localUsers =getLocalUsers();
for (User remoteUser : remoteUsers) {
boolean found = false;
for (User localUser : localUsers) {
if (remoteUser.equals(localUser)) {
found = true;
localUser.setActive(remoteUser.isActive());
localUser.setEmail(remoteUser.getEmail());
//update
}
break;
}
if (!found) {
User user = new User(remoteUser.getId(), remoteUser.getEmail(), remoteUser.isActive());
//Save
}
}
for(User localUser : localUsers ) {
boolean found = false;
for(User remoteUser : remoteUsers) {
if(localUser.equals(remoteUser)) {
found = true;
localUser.setActive(remoteUser.isActive());
localUser.setEmail(remoteUser.getEmail());
//Update
}
break;
}
if(!found) {
localUser.setActive(false);
// Deactivate
}
}
}
© Stack Overflow or respective owner