I would like to convert my map which looks like this:
{ key="someKey1", value=Apple(id="1", color="green"), key="someKey2", value=Apple(id="2", color="red"), key="someKey3", value=Apple(id="3", color="green"), key="someKey4", value=Apple(id="4", color="red"), }
to another map which puts all apples of the same color into the same list:
{ key="red", value=list={apple1, apple3}, key="green", value=list={apple2, apple4}, }
I tried the following:
Map<String, Set<Apple>> sortedApples = appleMap.entrySet() .stream() .collect(Collectors.toMap(l -> l.getColour, ???));
Am I on the right track? Should I use filters for this task? Is there an easier way?
Collectors.groupingBy
is more suitable than Collectors.toMap
for this task (though both can be used).
Map<String, List<Apple>> sortedApples = appleMap.values() .stream() .collect(Collectors.groupingBy(Apple::getColour));
Or, to group them into Set
s use:
Map<String, Set<Apple>> sortedApples = appleMap.values() .stream() .collect(Collectors.groupingBy(Apple::getColour, Collectors.mapping(Function.identity(), Collectors.toSet())));
or (as Aomine commented):
Map<String, Set<Apple>> sortedApples = appleMap.values() .stream() .collect(Collectors.groupingBy(Apple::getColour, Collectors.toSet()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With