【发布时间】:2020-06-09 15:30:49
【问题描述】:
这是我的列表 fooList
class Foo {
private String name;
private int code;
private int account;
private int time;
private String others;
... constructor, getters & setters
}
例如(帐户的所有值都已设置为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