Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambdas grouping reducing and mapping

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?

like image 343
Robert Bain Avatar asked Apr 16 '26 22:04

Robert Bain


1 Answers

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.

like image 53
Tagir Valeev Avatar answered Apr 18 '26 11:04

Tagir Valeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!