项目里随便找的一段代码
Map<String, CustomerStats> result =
orders.stream()
.filter(order -> "completed".equals(order.getStatus()) && order.getDate().isAfter(LocalDate.of(2022, 12, 31)))
.map(order -> order)
.sorted(Comparator.comparing(Order::getAmount).reversed())
.collect(Collector.of(
HashMap::new,
(map, order) -> map.compute(order.getCustomerId(),
(key, stats) -> {
if (stats == null) {
stats = new CustomerStats(0.0, 0);
}
stats.update(order.getAmount());
return stats;
}),
(map1, map2) -> {
map2.forEach((customerId, stats) -> map1.compute(customerId,
(key, existingStats) -> {
if (existingStats == null) {
return stats;
} else {
return existingStats.merge(stats);
}
}));
return map1;
},
Function.identity(),
Collector.Characteristics.UNORDERED
));