我正在尝试使用 Java-8 lambdas 来解决以下问题:
给定 a List<Transaction>
,对于每个,Category.minorCategory
我需要Transaction.amount
perCategory.minorCategory
和 a Map
ofTransaction.accountNumber
的总和以及Transaction.amount
per的总和Transaction.accountNumber
。根据下面的代码,我有这个工作。我现在需要分组Category.majorCategory
,基本上返回一个Map<String, Map<String, MinorCategorySummary>>
键控Category.majorCategory
。
我已经完成了所有工作,直到分组阶段,Category.majorCategory
但很难找到解决方案;使用 lambda 进行编程的范式转变证明了一条陡峭的学习曲线。
TransactionBreakdown
是动作发生的地方,我想返回一个Map<String, Map<String, MinorCategorySummary>>
.
public class Transaction {
private final String accountNumber;
private final BigDecimal amount;
private final Category category;
}
public class Category {
private final String majorCategory;
private final String minorCategory;
}
public class MinorCategorySummary {
private final BigDecimal sumOfAmountPerMinorCategory;
private final Map<String, BigDecimal> accountNumberSumOfAmountMap;
private final Category category;
}
public class TransactionBreakdown {
Function<Entry<String, List<Transaction>>, MinorCategorySummary> transactionSummariser = new TransactionSummariser();
public Map<Object, MinorCategorySummary> getTransactionSummaries(List<Transaction> transactions) {
return transactions
.stream()
.collect(groupingBy(t -> t.getCategory().getMinorCategory()))
.entrySet()
.stream()
.collect(
toMap(Entry::getKey,
transactionSummariser));
}
}
public class TransactionSummariser implements Function<Entry<String, List<Transaction>>, MinorCategorySummary> {
@Override
public MinorCategorySummary apply(
Entry<String, List<Transaction>> entry) {
return new MinorCategorySummary(
entry.getValue()
.stream()
.map(Transaction::getAmount)
.collect(reducing(BigDecimal.ZERO, BigDecimal::add)),
entry.getValue()
.stream()
.collect(
groupingBy(Transaction::getAccountNumber,
mapping(Transaction::getAmount,
reducing(BigDecimal.ZERO, BigDecimal::add)))),
entry.getValue().get(0).getCategory());
}
}