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:
Here
collectingAndThenused twice: once for downstreamCollectorto convert lists to theResultantDTOobjects and once to convert the resulting map to list of its values.