Home > Blockchain >  How do I compare two lists of objects and update values of specified properties with defferent value
How do I compare two lists of objects and update values of specified properties with defferent value

Time:07-23

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.

CodePudding user response:

try this

     list2.stream().filter(list2obj->list2obj.getUserId()==list1obj.getUserId())
                .forEach(objectWithMatchingId->{
                    if(list1obj.getAddress()!=objectWithMatchingId.getAddress())
                    list1obj.setAddress(objectWithMatchingId.getAddress());
                
                });
    });

CodePudding user response:

userList2
    .forEach(userObj2 -> userList1
        .stream()
        .filter(userObj1 -> userObj1.getUserId().equals(userObj2.getUserId())
            && !userObj1.getAddress().equals(userObj2.getAddress()))
        .forEach(userObj1 -> userObj1.setAddress(userObj2.getAddress()))
    );

}

  • Related