Answer the question
In order to leave comments, you need to log in
Java Stream: Is it possible to do object aggregation?
There is a list of object objects:
{type : CAT, count : 1},
{type : CAT, count : 2},
{type : DOG, count : 5},
{type : CAT, count : 3}, // 1 + 2
{type : DOG, count : 5},
Answer the question
In order to leave comments, you need to log in
The author of the question is lost, I will have to offer possible options. I'll start with the simplest - grouping in the Map with the appropriate collector:
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(Animal::getType,
Animal::getCount,
(a, b) -> a + b));
Map<String, Integer> map = list.stream()
.collect(Collectors.groupingBy(Animal::getType,
Collectors.summingInt(Animal::getCount)));
List<Animal> aggregated
= list.stream()
.collect(Collector.of(HashMap<String, Integer>::new,
(acc, val) -> acc.compute(val.getType(), (k, v) -> v == null ? val.getCount() : v + val.getCount()),
(l, r) -> {
l.replaceAll((k, v) -> v + r.getOrDefault(k, 0));
return l;
},
acc -> acc.entrySet()
.stream()
.map(e -> new Animal(e.getKey(), e.getValue()))
.collect(Collectors.toList())));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question