How to map a field of Object from one page with the Object from another page based on the Id field in Java 8

Viewed 92

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

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)));
});
Related