如何根据Java 8中的ID字段从一个页面上从一个页面中映射对象字段

发布于 2025-01-23 09:00:52 字数 831 浏览 0 评论 0原文

我有两个春季页 喜欢这样:page< account> and page< bank>

class Account{
    String name;
    String bankId;
    Bank bank;
}

我想为page< account>中的每个accode对象提供setBank(),并从page&lt< bank>带有相应的对象。基于bankid

我想我可以使用Java 8流。

到目前为止,我尝试过:

Map<String, Account> acc = account.stream()
           .collect(Collectors.toMap(Account::getBankId, a -> a));

List<Bank> bk = bank.stream()
           .map(b-> new Account(b.get(b.getBankId()), bk))
           .collect(Collectors.toList());

I have two Spring Pages like this : Page<Account> and Page<Bank>.

class Account{
    String name;
    String bankId;
    Bank bank;
}

I would like to setBank() for every Account object in the Page<Account> with the corresponding object from Page<Bank> based on the bankId.

I think I can use Java 8 streams for that.

So far, I've tried :

Map<String, Account> acc = account.stream()
           .collect(Collectors.toMap(Account::getBankId, a -> a));

List<Bank> bk = bank.stream()
           .map(b-> new Account(b.get(b.getBankId()), bk))
           .collect(Collectors.toList());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝眸 2025-01-30 09:00:52

我想每个银行将有一个以上的帐户。因此,代替map&lt; string,帐户&gt;您需要map&lt; string,list&lt; account&gt;&gt; - Charge> CharterbyBankId。可以通过使用build-in collector collector.groupingby()

Then you can map every bank to its id Map with Collectors.toMap().

And finally, set the bank object retrieved from the bankById map to every account in the map accountsByBankId.

Map<String, List<Account>> accountsByBankId = account.stream()
    .collect(Collectors.groupingBy(Account::getBankId));
    
Map<String, Bank> bankById = bank.stream()
    .collect(Collectors.toMap(Bank::getBankId, Function.identity()));
        
accountsByBankId.forEach((bankId, accounts) -> {
    accounts.forEach(acc -> acc.setBank(bankById.get(bankId)));
});

I guess there will be more than one account in each bank. So instead of Map<String, Account> you need a Map<String, List<Account>> - accountsByBankId. Which can be created by using build-in collector Collectors.groupingBy().

Then you can map every bank to its id Map<String, Bank> with Collectors.toMap().

And finally, set the bank object retrieved from the bankById map to every account in the map accountsByBankId.

Map<String, List<Account>> accountsByBankId = account.stream()
    .collect(Collectors.groupingBy(Account::getBankId));
    
Map<String, Bank> bankById = bank.stream()
    .collect(Collectors.toMap(Bank::getBankId, Function.identity()));
        
accountsByBankId.forEach((bankId, accounts) -> {
    accounts.forEach(acc -> acc.setBank(bankById.get(bankId)));
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文