【发布时间】:2022-11-21 05:38:40
【问题描述】:
这是我的列表 fooList
class Foo {
private String name;
private int code;
private int account;
private int time;
private String others;
... constructor, getters & setters
}
例如(account的所有值都设置为1)
new Foo(First, 200, 1, 400, other1),
new Foo(First, 200, 1, 300, other1),
new Foo(First, 201, 1, 10, other1),
new Foo(Second, 400, 1, 20, other2),
new Foo(Second, 400, 1, 40, other2),
new Foo(Third, 100, 1, 200, other3),
new Foo(Third, 101, 1, 900, other3)
我想通过对“名称”和“代码”进行分组、计算数量并对“时间”求和来转换这些值,例如
new Foo(First, 200, 2, 700, other1),
new Foo(First, 201, 1, 10, other1),
new Foo(Second, 400, 2, 60, other2),
new Foo(Third, 100, 1, 200, other3),
new Foo(Third, 101, 1, 900, other3)
我知道我应该使用这样的流:
Map<String, List<Foo>> map = fooList.stream().collect(groupingBy(Foo::getName()));
但是我怎样才能按代码对它们进行分组然后进行会计和汇总工作呢?
另外,如果我想计算平均时间怎么办?例如
new Foo(First, 200, 2, 350, other1),
new Foo(First, 201, 1, 10, other1),
new Foo(Second, 400, 2, 30, other2),
new Foo(Third, 100, 1, 200, other3),
new Foo(Third, 101, 1, 900, other3)
我可以同时使用summingInt(Foo::getAccount) 和averagingInt(Foo::getTime) 吗?
【问题讨论】:
-
为什么当你传递整数值时你的名字是字符串?
-
也许我应该以更好的方式重命名它@MrFisherman
标签: java lambda java-stream grouping