GroupingByConcurrent Parallel Rollup
Aggregate parallel streams straight into ConcurrentMaps with groupingByConcurrent and toConcurrentMap, supplying the merge function key conflicts require.
Code
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())));
}
}Inside the snippet
All of the logic lives in the classes ConcurrentRollup and Event and the function main.
The pipeline is a stream: source, lazy intermediate steps, one terminal collector.
Using it
The main signature reads public static void main(String[] args)
Key statements
.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())));
Interactive Tools for This Topic
FAQ
- How do you run GroupingByConcurrent Parallel Rollup?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.