如何根据现有地图中的值创建新地图 [英] How create a new map from the values in an existing map
问题描述
拥有下一个原始地图:
G1=[7,8,45,6,9]
G2=[3,9,34,2,1,65]
G3=[6,5,9,1,67,5]
如果G1,G2和G3是人们年龄的组合,我该如何创建这样的新地图:
Where G1, G2 and G3 are groups of people's ages, How can I create a new map like this:
45=[7,8,45,6,9]
65=[3,9,34,2,1,65]
67=[6,5,9,1,67,5]
新密钥是每个人的最大年龄分组。
Where the new keys are the max people's age in each group.
我试过这个:
Map<Integer, List<Integer>> newMap = originalMap.entrySet().stream()
.collect(Collectors.toMap(Collections.max(x -> x.getValue()), x -> x.getValue()));
但是编译器说我:这个表达式的目标类型必须是一个功能接口代码片段:
But the compiler say me: "The target type of this expression must be a functional interface" in this fragment of code:
Collections.max(x -> x.getValue())
我们将不胜感激。
推荐答案
toMap使用它的 keyMapper
和 valueMapper
的函数。您正在为代码中的 valueMapper
正确执行此操作,但不能为 keyMapper
执行此操作,因此您需要包含 keyMapper
函数如下:
toMap consumes function for it's keyMapper
and valueMapper
. You're doing this correctly for the valueMapper
in your code but not for the keyMapper
thus you need to include the keyMapper
function as follows:
originalMap.entrySet()
.stream()
.collect(toMap(e -> Collections.max(e.getValue()), Map.Entry::getValue));
请注意 e - > Collections.max(e.getValue())
。
note the e -> Collections.max(e.getValue())
.
此外,由于您没有使用地图键,你可以避免调用entrySet()而是处理地图值:
Further, since you're not working with the map keys, you can avoid having to call entrySet() and instead work on the map values:
originalMap.values()
.stream()
.collect(Collectors.toMap(Collections::max, Function.identity()));
这篇关于如何根据现有地图中的值创建新地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!