Java 8 Lambdas - How to Sum and Averages from a Stream

Is it possible to sum and average and convert to a new object from the stream. I have an object

    public class Foo {
       private String code;
       private double price;
      ....
    }

Now I want to get the average value and summarize this list of objects (the sum of the price by code and the average price by code)

 foos = Arrays.asList(
            new Foo("MTN" , 200 ),
            new Foo("MTN" , 210 ),
            new Foo("MTN" , 205 ),
            new Foo("OMT" , 300 ),
            new Foo("OMT" , 320 ),
            new Foo("OMT" , 310 ),
            new Foo("AAA" , 650 ),
            new Foo("AAA" , 680 ),
            new Foo("AAA" , 600 ));

Then I would like to create a new object (FooB

    public class FooB {
       private String code;
       private double total;
       private double average;
       ....
   }

This is what I now have, but I double-scan the stream. I need a method where I can do this by going through the stream once.

 Map<String, Double> averagePrices = foos.stream()
            .collect(
                    Collectors.groupingBy(
                   Foo::getCode,Collectors.averagingDouble(Foo::getPrice)));



    Map<String, Double> totalPrices = foos.stream()
            .collect(
                    Collectors.groupingBy(
                            Foo::getCode,
                            Collectors.summingDouble(Foo::getPrice)));


    List<FooB > fooBs = new ArrayList<>();
    averagePrices.forEach((code, averageprice)-> {
        FooB fooB = new FooB (code , totalPrices.get(code)  , averageprice);
        fooBs.add(fooB );
    });

    fooBs.forEach(e -> System.out.println(e.toString()));

Is there a better way to do this without repeating this. Thanks

+4
source share
1 answer

You can use DoubleSummaryStatisticsto save both results before matching with FooB:

Map<String, DoubleSummaryStatistics> data = foos.stream()
                .collect(Collectors.groupingBy(Foo::getCode,
                                    Collectors.summarizingDouble(Foo::getPrice)));

List<FooB> fooBs = data.entrySet().stream()
        .map(e -> new FooB(e.getKey(), e.getValue().getSum(), e.getValue().getAverage()))
        .collect(toList());
+8
source

All Articles