Home  >  Article  >  Java  >  How to Perform Nested GroupBy Operations in Java 8 for Complex Data Aggregation?

How to Perform Nested GroupBy Operations in Java 8 for Complex Data Aggregation?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 08:50:02566browse

How to Perform Nested GroupBy Operations in Java 8 for Complex Data Aggregation?

Nested (Multi-Level) GroupBy in Java 8

Multi-level grouping in Java 8 allows for complex aggregation of data objects based on multiple fields. In your case, you have a set of classes Pojo, Item, and SubItem, and you want to group items based on key1 and then subitems within that group by key2.

To achieve this, we can't simply use nested Collectors.groupingBy calls, as this would not allow for grouping by multiple keys from different objects. Instead, we resort to a combination of flatMap and grouping collectors:

<code class="java">Map<T, Map<V, List<SubItem>>> result = pojo.getItems().stream()
    .flatMap(item -> item.getSubItems().stream()
        .map(sub -> new AbstractMap.SimpleImmutableEntry<>(item.getKey1(), sub)))
    .collect(Collectors.groupingBy(AbstractMap.SimpleImmutableEntry::getKey,
                Collectors.groupingBy(Map.Entry::getValue, Collectors.toList())));</code>

In this approach, we first use flatMap to create a stream of pairs containing the key1 from each Item and the corresponding SubItem. Then, we apply Collectors.groupingBy twice: once to group the pairs by key1 and again to group the SubItems by key2.

An alternative solution would be to define a custom collector that provides a flatMapping operation similar to Java 9's Collectors.flatMapping:

<code class="java">static <T,U,A,R> Collector<T,?,R> flatMapping(
    Function<? super T,? extends Stream<? extends U>> mapper,
    Collector<? super U,A,R> downstream) {

    BiConsumer<A, ? super U> acc = downstream.accumulator();
    return Collector.of(downstream.supplier(),
        (a, t) -> { try(Stream<? extends U> s=mapper.apply(t)) {
            if(s!=null) s.forEachOrdered(u -> acc.accept(a, u));
        }},
        downstream.combiner(), downstream.finisher(),
        downstream.characteristics().toArray(new Collector.Characteristics[0]));
}</code>

With this custom collector, the grouping operation can be simplified:

<code class="java">Map<T, Map<V, List<SubItem>>> result = pojo.getItems().stream()
    .collect(Collectors.groupingBy(Item::getKey1,
                Collectors.flatMapping(item -> item.getSubItems().stream(),
                    Collectors.groupingBy(SubItem::getKey2))));</code>

The above is the detailed content of How to Perform Nested GroupBy Operations in Java 8 for Complex Data Aggregation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn