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