Posts

Showing posts from April 23, 2019

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

Image
7 1 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?