简体   繁体   English

Java 8 Streams - 从流中对类型中的多个值求和

[英]Java 8 Streams - summing multiple values in a type from a stream

I'm trying to sum the sum of two variables within a class which are streamed from a collection. 我试图将一个从集合中流式传输的类中的两个变量的总和相加。 Consider the following simple class. 考虑以下简单类。

class Widget {
    String colour;
    Double legs;
    Double arms;
    // ...
}

I want to stream a collection of Widgets, group them by colour and work out the sum of (legs + arms) to find the total number of limbs for each colour. 我想要流式传输一个小部件集合,按颜色对它们进行分组并计算出(腿+臂)的总和,以找出每种颜色的肢体总数。

I want to do something simple, like this - 我想做一些简单的事情,比如这样 -

widgets.stream().collect(groupingBy(Widget::getColour, summingDouble(legs + arms)));

However, there's no Collectors function which allows me to specify a custom value to sum. 但是,没有Collectors函数允许我指定自定义值来求和。

My question is: Do I need to write a custom Collector or is there another easy way to achieve what I want? 我的问题是:我是否需要编写自定义收集器或是否有另一种简单的方法来实现我想要的?

You shall alternatively use toMap here as: 你也可以在这里使用toMap

Map<String, Double> colorToLimbsCount = widgets.stream()
        .collect(Collectors.toMap(Widget::getColour,
                widget -> widget.getArms() + widget.getLegs(), Double::sum));

in the groupingBy representation, it could look like: groupingBy表示中,它可能看起来像:

Map<String, Double> colorToLimbsCount = widgets.stream()
        .collect(Collectors.groupingBy(Widget::getColour,
                Collectors.reducing((double) 0,
                        widget -> widget.getArms() + widget.getLegs(), Double::sum)));

You can just use Collectors.summingDouble() : 你可以使用Collectors.summingDouble()

Map<String, Double> result = widgets.stream()
        .collect(Collectors.groupingBy(
                Widget::getColour,
                Collectors.summingDouble(w -> w.getArms() + w.getLegs())
        ));

You can just use the function w -> w.getArms() + w.getLegs() to sum the arms and legs. 您可以使用函数w -> w.getArms() + w.getLegs()来对手臂和腿进行求和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM