简体   繁体   中英

How do I compare two lists of objects and update values of specified properties with defferent values?

I have two lists of objects like this,

List<UserDTO> userList1;
List<UserDTO> userList2;

UserDTO

public class UserDTO {
  private userId;
  private name;
  private phone;
  private address;
}

Both lists have a list of UserDTO . I am trying to iterate through list 1 and see if there's any object with same userId from list 1 is present in list 2. If it is present then I want to check whether address property of both objects from list 1 and list 2 matches. If it does not match then I want update address of list 1 with list 2.

try this

     list2.stream().filter(list2obj->list2obj.getUserId()==list1obj.getUserId())
                .forEach(objectWithMatchingId->{
                    if(list1obj.getAddress()!=objectWithMatchingId.getAddress())
                    list1obj.setAddress(objectWithMatchingId.getAddress());
                
                });
    });
userList2
    .forEach(userObj2 -> userList1
        .stream()
        .filter(userObj1 -> userObj1.getUserId().equals(userObj2.getUserId())
            && !userObj1.getAddress().equals(userObj2.getAddress()))
        .forEach(userObj1 -> userObj1.setAddress(userObj2.getAddress()))
    );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM