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"
}
I would like to convert this to a list of objects that looks like this:
{
value=800
category="GROCERY"
},
{
value=300
category="FUEL"
},
{
value=300
category="SMALL APPLIANCE REPAIR"
}
Basically, all the values with the same category are added up.
Should I use flatMap? Reduce? I do not understand its nuances to understand this.
reference
EDIT:
There are close duplicates of this question:
Is there an aggregateBy method in the Java 8 api thread? as well as the
Sum attribute of the object with the Stream API
But in both cases, the end result is a map, not a list
The last solution I used based on the answers of @AndrewTobilko and @JBNizet was:
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());