Java 8:具有列表嵌套类的收集器groupby [英] Java 8: Collector groupby with list nested class

查看:214
本文介绍了Java 8:具有列表嵌套类的收集器groupby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Java 8来关注Map

I am trying to get following Map via Java 8

Class One {
    String one;
    List <Two> two;
}

Class Two {
    BigDecimal bd;
}

如何收集包含按One.one(即map的第一个参数)分组的Map.对于Two.bd的映射和的第二个参数.

How do I collect a Map which contains grouping by One.one i.e., first parameter of map. For second parameter of map sum of Two.bd.

推荐答案

您可以使用此

List<One> list = ...;

Map<String, BigDecimal> result1 = list.stream()
    .collect(Collectors.groupingBy(One::getOne, // key is One.one
        Collectors.mapping(one -> one.getTwo().stream() // get stream of One.two
            .map(Two::getBd) // map to Bd
            .reduce(BigDecimal.ZERO, BigDecimal::add), // reduce to sum
            Collectors.reducing(BigDecimal.ZERO, BigDecimal::add) // sum sums
        )
    ));

这将对Two的所有bd求和,然后对具有相同oneOne的总和求和.

This will sum all the bd of Two, and then also sum the sums for Ones that have the same one.

如果Java8具有flatMapping收集器,则事情会更简单,但已将其添加到 Java9 :

Although things would be simpler if Java8 had a flatMapping collector, one has been added to Java9:

public 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> downstreamAccumulator = downstream.accumulator();
    return Collector.of(downstream.supplier(),
                        (r, t) -> mapper.apply(t).sequential().forEach(u -> downstreamAccumulator.accept(r, u)),
                        downstream.combiner(),
                        downstream.finisher(),
                        downstream.characteristics().stream().toArray(Collector.Characteristics[]::new));
}

哪个会做到:

Map<String, BigDecimal> result1 = list.stream()
    .collect(Collectors.groupingBy(One::getOne,
        flatMapping(one -> one.getTwo().stream().map(Two::getBd),
            Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)
        )
    ));

这篇关于Java 8:具有列表嵌套类的收集器groupby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆