我们有以下内容:
public List<Balance> mapToBalancesWithSumAmounts(List<MonthlyBalancedBooking> entries) {
return entries
.stream()
.collect(
groupingBy(
MonthlyBalancedBooking::getValidFor,
summingDouble(MonthlyBalancedBooking::getAmount)
)
)
.entrySet()
.stream()
.map(localDateDoubleEntry -> new Balance(localDateDoubleEntry.getValue(), localDateDoubleEntry.getKey()))
.collect(toList());
}
是否有可能避免代码中的第二个stream()路径,因此在我们的例子中groupingBy()的结果应该是一个列表。我们需要将map()函数传递给collect或groupingBy,这在Java 8中可能吗?
最佳答案
这是不可能的,因为您在映射到 Balance
对象时查找的值只能在 MonthlyBalancedBooking
列表的所有条目都被评估后才能计算进行迭代。
new Balance(localDateDoubleEntry.getValue(), localDateDoubleEntry.getKey())
在单个终端操作中移动流的另一种方法可以是使用 collectingAndThen
作为:
public List<Balance> mapToBalancesWithSumAmounts(List<MonthlyBalancedBooking> entries) {
return entries.stream()
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(MonthlyBalancedBooking::getValidFor,
Collectors.summingDouble(MonthlyBalancedBooking::getAmount)),
map -> map.entrySet().stream()
.map(entry -> new Balance(entry.getValue(), entry.getKey()))))
.collect(Collectors.toList());
}
关于java - GroupingBy 和 List 作为结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60862618/