I have a List fooList
class Foo {
private String category;
private int amount;
private int price;
... constructor, getters & setters
}
I would like to group by category and then sum amount aswell as price.
The result will be stored in a map:
Map<Foo, List<Foo>> map = new HashMap<>();
The key is the Foo holding the summarized amount and price, with a list as value for all the objects with the same category.
So far I've tried the following:
Map<String, List<Foo>> map = fooList.stream().collect(groupingBy(Foo::getCategory()));
Now I only need to replace the String key with a Foo object holding the summarized amount and price. Here is where I'm stuck. I can't seem to find any way of doing this.
A bit ugly, but it should work:
list.stream().collect(Collectors.groupingBy(Foo::getCategory))
.entrySet().stream()
.collect(Collectors.toMap(x -> {
int sumAmount = x.getValue().stream().mapToInt(Foo::getAmount).sum();
int sumPrice= x.getValue().stream().mapToInt(Foo::getPrice).sum();
return new Foo(x.getKey(), sumAmount, sumPrice);
}, Map.Entry::getValue));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With