Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Map<String, Object> to Map<String, Set<Object>> with filter and streams

Tags:

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?

like image 951
M4V3N Avatar asked Jan 02 '19 11:01

M4V3N


1 Answers

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 Sets 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())); 
like image 182
Eran Avatar answered Nov 10 '22 19:11

Eran