Java 8 adding values of multiple property of an Object List
It seems that you need to group based on three things: Year
, Month
and Name
, so this could look like this:
Collection<Target> merged = yourListOfTargets
.stream()
.collect(Collectors.toMap(
t -> List.of(t.getYear(), t.getMonth(), t.getName()),
Function.identity(),
(left, right) -> {
left.setTarget(left.getTarget() + right.getTarget());
left.setAchieved(left.getAchieved() + right.getAchieved());
return left;
}))
.values();
As Federico mentions in comments, this will alter your elements in the initial List
. You might be OK with it, but if you are not, you need to replace Function.identity()
with a copying Function that would create a new Target
from an existing one.