繁体   English   中英

如何比较两个对象列表并使用不同值更新指定属性的值?

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

我有两个这样的对象列表,

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

用户DTO

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

两个列表都有一个UserDTO列表。 我正在尝试遍历列表 1,并查看列表 2 中是否存在与列表 1 中具有相同userId的任何对象。如果存在,那么我想检查列表 1 和列表 2 中两个对象的address属性是否匹配。 如果它不匹配,那么我想用列表 2 更新列表 1 的地址。

尝试这个

     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()))
    );

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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