Given a List of the following Transaction class, using Java 8 lambdas, I want to obtain a List of ResultantDTO, one per account type.
public class Transaction {
private final BigDecimal amount;
private final String accountType;
private final String accountNumber;
}
public class ResultantDTO {
private final List<Transaction> transactionsForAccount;
public ResultantDTO(List<Transaction> transactionsForAccount){
this.transactionsForAccount = transactionsForAccount;
}
}
So far, I use the following code to group the List<Transaction> by accountType.
Map<String, List<Transaction>> transactionsGroupedByAccountType = transactions
.stream()
.collect(groupingBy(Transaction::getAccountType));
How do I return a List<ResultantDTO>, passing the List from each map key into the constructor, containing one ResultantDTO per accountType?
You can do this in single stream operation:
public List<ResultantDTO> convert(List<Transaction> transactions) {
return transactions.stream().collect(
collectingAndThen(
groupingBy(
Transaction::getAccountType,
collectingAndThen(toList(), ResultantDTO::new)),
map -> new ArrayList<>(map.values())));
}
Here collectingAndThen used twice: once for downstream Collector to convert lists to the ResultantDTO objects and once to convert the resulting map to list of its values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With