我们有以下内容:
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()-function或groupingBy的可能性,在Java8中这是可能的吗?
发布于 2020-03-26 15:32:06
简单的方法是使用具有合并功能的toMap()收集器,如下所示:
List<Balance> balances = new ArrayList<>(entries.stream()
.collect(toMap(MonthlyBalancedBooking::getValidFor, m -> new Balance(m.getAmount(),
m.getValidFor()),Balance::merge)).values());我假设对于Balance类有以下属性:
class Balance {
private Double value;
private Integer key;
public Balance merge(Balance b) {
this.value += b.getValue();
return this;
}
}发布于 2020-03-26 16:27:07
这是不可能的,因为映射到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());
}https://stackoverflow.com/questions/60862618
复制相似问题