实现说明
Collectors 分区与分组的核心是类 PartitionRollup、Order和函数 main。
管道就是一个 stream:数据源、惰性中间步骤、一个终端收集器。
使用要点
- 跑完文件,输出里会留下标记——
rush count =、standard count =。
常见问题
运行「Collectors 分区与分组」会打印什么?
运行文件本身,rush count =、standard count = 这些前缀各对应一段演示逻辑。
核心语句
orders.stream().collect(Collectors.groupingBy(Order::region, Collectors.counting()));
orders.stream().collect(Collectors.partitioningBy(Order::rush));
orders.stream().collect(Collectors.groupingBy(Order::region,
Collectors.averagingInt(Order::amount)));
代码示例
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class PartitionRollup {
record Order(String region, int amount, boolean rush) {}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("eu", 120, true),
new Order("eu", 80, false),
new Order("na", 95, false),
new Order("na", 210, true),
new Order("apac", 45, false));
// partitioningBy 恒产生 true/false 两个桶(即使为空)
Map<Boolean, List<Order>> byRush =
orders.stream().collect(Collectors.partitioningBy(Order::rush));
System.out.println("rush count = " + byRush.get(true).size());
System.out.println("standard count = " + byRush.get(false).size());
// groupingBy + downstream:每区域订单数与平均金额
Map<String, Long> countByRegion =
orders.stream().collect(Collectors.groupingBy(Order::region, Collectors.counting()));
Map<String, Double> avgByRegion =
orders.stream().collect(Collectors.groupingBy(Order::region,
Collectors.averagingInt(Order::amount)));
countByRegion.forEach((region, count) ->
System.out.printf("%s: %d orders, avg %.1f%n", region, count, avgByRegion.get(region)));
}
}