Search code examples
javajava-8functional-programmingjava-streamcollectors

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.

My question is: Do I need to write a custom Collector or is there another easy way to achieve what I want?


Solution

  • You can just use 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.