I have a simple Foo class:
class Foo {
String type;
Integer quantity;
String code;
}
and a list of objects of this type:
{ type=11, quantity=1, code=A },
{ type=11, quantity=2, code=A },
{ type=11, quantity=1, code=B },
{ type=11, quantity=3, code=C },
{ type=12, quantity=2, code=A },
{ type=12, quantity=1, code=B },
{ type=11, quantity=1, code=B },
{ type=13, quantity=1, code=C },
{ type=13, quantity=3, code=C }
I need to group by type first, and I can do this:
Map<String, List<Foo>> typeGroups = mylist.stream().collect(Collectors.groupingBy(Foo::getType));
The next step will convert the value Mapto List<Foo>as follows:
{ type=11, quantity=3, code=A },
{ type=11, quantity=2, code=B },
{ type=11, quantity=3, code=C },
{ type=12, quantity=2, code=A },
{ type=12, quantity=1, code=B },
{ type=13, quantity=4, code=C }
In SQL, I will have a query like this:
SELECT type, code, SUM(quantity) FROM Foo GROUP BY type, code
Let me explain in plain English.
I need to get a list of backgrounds. Each one code must be unique among its group, and the quantity must be the total amount of Foos having the same code among its group.
I tried to do this using groupingBy()c summingInt(), but not getting the desired result.