实现说明
GroupingByConcurrent 并行聚合可以归结为类 ConcurrentRollup、Event和函数 main。
管道就是一个 stream:数据源、惰性中间步骤、一个终端收集器。
常见问题
「GroupingByConcurrent 并行聚合」这个示例怎么运行?
运行这个文件就行;脚本没有任何外部要求。
核心语句
.collect(Collectors.groupingByConcurrent(Event::region, Collectors.counting()));
.collect(Collectors.toConcurrentMap(
Event::region,
Event::ms,
Integer::max));
countByRegion.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(e -> System.out.printf(
"%s: %d events, worst %d ms%n",
e.getKey(), e.getValue(), worstByRegion.get(e.getKey())));
代码示例
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
public class ConcurrentRollup {
record Event(String region, int ms) {}
public static void main(String[] args) {
List<Event> events = List.of(
new Event("eu", 120),
new Event("eu", 80),
new Event("na", 95),
new Event("na", 210),
new Event("apac", 45));
// groupingByConcurrent:分组聚合直接进 ConcurrentMap,可安全并行遍历
ConcurrentMap<String, Long> countByRegion = events.parallelStream()
.collect(Collectors.groupingByConcurrent(Event::region, Collectors.counting()));
// toConcurrentMap:键冲突必须给合并函数,否则抛 IllegalStateException
ConcurrentMap<String, Integer> worstByRegion = events.parallelStream()
.collect(Collectors.toConcurrentMap(
Event::region,
Event::ms,
Integer::max));
countByRegion.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(e -> System.out.printf(
"%s: %d events, worst %d ms%n",
e.getKey(), e.getValue(), worstByRegion.get(e.getKey())));
}
}