Friday, March 12, 2010

Update a list from another list

Programmer Question

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:




  1. If a remote user already exists locally, update its fields.

  2. If a remote user doesn't already exist locally, add the user.

  3. If a local user doesn't appear in the remote list, deactivate or delete.

  4. 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
}
}
}


Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails