我想转换我的 map ,如下所示:
{
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"),
}
到另一张 map ,它将所有相同颜色的苹果放在同一个列表中:
{
key="red", value=list={apple1, apple3},
key="green", value=list={apple2, apple4},
}
我尝试了以下方法:
Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
.stream()
.collect(Collectors.toMap(l -> l.getColour, ???));
我在正确的轨道上吗?我应该为此任务使用过滤器吗?有没有更简单的方法?
最佳答案
Collectors.groupingBy
比 Collectors.toMap
更适合此任务(尽管两者都可以使用)。
Map<String, List<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour));
或者,要将它们分组到 Set
中,请使用:
Map<String, Set<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour,
Collectors.mapping(Function.identity(),
Collectors.toSet())));
或者(正如青峰评论的那样):
Map<String, Set<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour, Collectors.toSet()));
关于java - 使用过滤器和流将 Map<String, Object> 转换为 Map<String, Set<Object>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54005438/