Here is my List fooList
class Foo {
private String name;
private int code;
private int account;
private int time;
private String others;
... constructor, getters & setters
}
e.g.(all the value of account has been set to 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)
I want to transform these values by grouping "name" and "code", accounting for the number, and summing the "time", e.g.
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)
I know that I should use a stream like this:
Map<String, List<Foo>> map = fooList.stream().collect(groupingBy(Foo::getName()));
but how can I group them by code then do the accounting and summing job?
Also, what if I want to calculate the average time? e.g.
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)
Can I use both of summingInt(Foo::getAccount)
and averagingInt(Foo::getTime)
instead?