I have a list of users in local storage that I need to periodically update from a remote list of users. Primarily:
- If the remote user already exists locally, update its fields.
- If the remote user does not already exist locally, add the user.
- If the local user does not appear in the remote list, deactivate or delete.
- If the local user also appears in the remote list, update its fields. (Same as 1)
Eg. Remote list: user (1, true), user (2, true), user (4, true), user (5, true)
Local list: user (1, true), user (2, false), user (3, true), user (6, true)
New local list: user (1, true), user (2, true), user (3, false), user (4, true), user (5, true), user (6, / p>
Just a simple example of local list synchronization. Is there a better way to do this in pure Java than the following? I feel rude looking at my own code.
public class User {
Integer id;
String email;
boolean active;
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) {
List<User> remoteUsers = getRemoteUsers();
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());
}
break;
}
if (!found) {
User user = new User(remoteUser.getId(), remoteUser.getEmail(), remoteUser.isActive());
}
}
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());
}
break;
}
if(!found) {
localUser.setActive(false);
}
}
}