Java流分组并汇总多个字段
我有一个列表 fooList
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.
结果将存储在地图中:
Map<Foo, List<Foo>> map = new HashMap<>();
关键是 Foo 持有汇总的金额和价格,并带有一个列表作为所有具有相同类别的对象的值.
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()));
现在我只需要将字符串键替换为包含汇总金额和价格的 Foo 对象.这是我卡住的地方.我似乎找不到任何方法.
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));
相关文章