java—如何迭代并用另一个对象属性替换对象中的内部列表属性

wz8daaqr  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(440)

我想换新的 state 使用目标上的起始值的字符串。个人出发地/目的地地址由标识符匹配 addressId 对象结构

Person:
String name
List<Address> address

Address:
String addressId
String city
String state

Person originPerson = new Person();
originPerson.setName("Jon");

List<Address> address = new ArrayList();
Address address = new Address();
address.setAddressId("1");
address.setCity("Malibu");
address.setState("CA");
originPerson.setAddress(address);

Person destinationPerson = new Person();
destinationPerson.setName("Jon");

List<Address> address = new ArrayList();
Address address = new Address();
address.setAddressId("1");
address.setCity("Malibu");
address.setState("MI");
destinationPerson.setAddress(address);

方法

public Person stateReplacer(Person destination, Person origin){
        origin.getAddress().forEach(address -> {
            //CODE
        });
        return destination;
}

在这个例子中,我想用来自源的ca替换目标中的状态mi。
我在网上搜索了几个问题,但无法解决。谢谢。

2w2cym1i

2w2cym1i1#

根据您所描述的,类似的方法应该可以工作(如果您绝对确定api响应不能有null或空的源地址,并且地址id将始终具有匹配项)。

public Person stateReplacer(Person origin, Person destination){
    boolean hasOneAddress = origin.getAddress().size() == 1;
    if (hasOneAddress) {
        String newState = origin.getAddress().get(0).getState();
        for (Address address : destination.getAddress()) {
            address.setState(newState);
        }
    }
    else {
        Map<String, String> addressIdStateMap = new HashMap<>();
        for (Address address : origin.getAddress()) {
            addressIdStateMap.put(address.addressId, address.state);

        }
        for (Address address : destination.getAddress()) {
            address.setState(addressIdStateMap.get(address.addressId));
        }
    }
    return destination;
}

相关问题