Having an instance of a Map<A, Set<B>>
where B
is a POJO with property Integer price
(among others), how do I elegantly transform this map into a Map<A, Integer>
where Integer
denotes the sum of prices
of a given set, for each key A
?
You can use stream like this:
Map<A, Integer> result = map.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
b -> b.getValue().stream()
.mapToInt(B::getPrice)
.sum()
));