Java stream group by and sum multiple fields(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));
这篇关于Java流分组并汇总多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java流分组并汇总多个字段


基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01