Reputation: 557
I need some help mapping a Map<String, List<Fee>>
with a List<FeeRequest>
.
Fee
object looks like this:
private String feeCode;
FeeRequest
objects looks like this:
private String feeCode;
private String debtorAccount;
So what I need is to map:
String debtorAccount(from map) -> debtorAccount(from List)
feeCode(from List from map) -> feeCode(from List)
I want to try not to use foreach
, but instead learn to properly use .stream().map()
features.
What I've managed to do:
Map<String, List<Fee>> feeAccounts
is parsed from another method.
List<FeeRequest> feeRequests = feeAccounts.entrySet().stream().map(feeAcc -> {
FeeRequest request = new FeeRequest();
request.setDebtorAccount(feeAcc.getKey());
request.setFeeCode(...);
return request;
}).collect(Collectors.toList());
I think that my approach is bad, but I don't know how to make it work. I tried looking at some examples but they're too basic. So I would be glad to get any help. Thanks!
Upvotes: 1
Views: 86
Reputation: 10300
If FeeRequest
has a constructor with two arguments you can use something like this:
feeAccounts.entrySet().stream()
.flatMap(
accountEntry -> accountEntry.getValue().stream().map(
fee -> new FeeRequest(
accountEntry.getKey(),
fee.getFeeCode()
)
)
).collect(toList());
Upvotes: 0
Reputation: 393841
If each Fee
instance should generate a FeeRequest
instance, you need flatMap
:
List<FeeRequest> feeRequests =
feeAccounts.entrySet()
.stream()
.flatMap(feeAcc -> feeAcc.getValue()
.stream()
.map(f -> {
FeeRequest request = new FeeRequest();
request.setDebtorAccount(feeAcc.getKey());
request.setFeeCode(f.getCode());
return request;
}))
.collect(Collectors.toList());
Upvotes: 1