java8流来基于列表沿着现有属性创建多个对象

new9mtju  于 2023-02-20  发布在  Java
关注(0)|答案(1)|浏览(111)

我有一个对象,我想创建多个对象的基础上的名单。
Account.java

class Account{
    @JsonProperty("accountId")
    private Long accountId;
    @JsonProperty("custId")
    private String custId;
    //custName, comments, status
    private String custCode;
    private LocalDate startOn;
    private String loanType;
}

示例输入请求json:

"accountRequest": [
    {
        "accountId": "10EIIP",
        "custId": "11EE",
        "custName": "XYZ",
        "comments": null,
        "status": "active",
        "linkedDetails": [
            {
                "custCode": "001",
                "startOn": "2023-01-01",
                "loanType": "auto"
            },
            {
                "custCode": "002",
                "startOn": "2023-01-15",
                "loanType": "home"
            },
            {
                "custCode": "003",
                "startOn": "2023-02-10",
                "loanType": "home"
            }
        ]
    }
]

示例java代码:

List<Account> accountList = new ArrayList<>();
List<AccountRequest> accountRequestList = request.getAccountRequest();
accountRequestList.get(0).getLinkedDetails().forEach(linkedDetails -> {
    Account account = new Account();
    //need to set accountId, custId, custName, comments, status in each account object along with below set values..
    account.setCustCode(linkedDetails.getCustCode());
    account.setStartOn(linkedDetails.getStartOn());
    account.setLoanType(linkedDetails.getLoanType());
    accountList.add(account);
});

从“accountRequest”对象,我想迭代“linkedDetails”,并根据linkedDetails的大小创建对象。

预期输出json:

"accountList": [
    {
        "accountId": "10EIIP",
        "custId": "11EE",
        "custName": "XYZ",
        "comments": null,
        "status": "active",
        "custCode": "001",
        "startOn": "2023-01-01",
        "loanType": "auto"
    },
    {
        "accountId": "10EIIP",
        "custId": "11EE",
        "custName": "XYZ",
        "comments": null,
        "status": "active",
        "custCode": "002",
        "startOn": "2023-01-15",
        "loanType": "home"
    },
    {
        "accountId": "10EIIP",
        "custId": "11EE",
        "custName": "XYZ",
        "comments": null,
        "status": "active",
        "custCode": "003",
        "startOn": "2023-02-10",
        "loanType": "home"
    }
]

在上面显示的示例Java代码中,accountId、custId、custName、comments和status属性为空且未复制。查找输出json,如预期输出所示。

bqucvtff

bqucvtff1#

你要做的就是这样。

List<Account> accounts = request.getAccountRequest().stream().flatMap(ac -> ac.getLinkedDetails().stream().map(ld -> {
            Account account = new Account();
            account.setAccountId(ac.getAccountId());
            account.setCustId(ac.getCustId());
            account.setCustCode(ld.getCustCode());
            account.setStartOn(ld.getStartOn());
            account.setLoanType(ld.getLoanType());

            return account;
        })).collect(Collectors.toList());

相关问题