I have a List of objects that look like this:
{
value=500
category="GROCERY"
},
{
value=300
category="GROCERY"
},
{
value=100
category="FUEL"
},
{
value=300
category="SMALL APPLIANCE REPAIR"
},
{
value=200
category="FUEL"
}
{
value=800
category="GROCERY"
},
{
value=300
category="FUEL"
},
{
value=300
category="SMALL APPLIANCE REPAIR"
}
List<MyClass> myClassList = list.stream()
.collect(Collectors.groupingBy(YourClass::getCategory,
Collectors.summingInt(YourClass::getValue)))
.entrySet().stream().map(e -> new MyClass(e.getKey(), e.getValue()).collect(toList());
With static import of the Collectors
class:
list.stream()
.collect(groupingBy(YourClass::getCategory,
summingInt(YourClass::getValue)));
You will get a map Map<String, Integer>
. Your class has to have getValue
and getCategory
methods to write method references, something like
public class YourClass {
...
public String getCategory() { return category; }
public int getValue() { return value; }
}