How create a new map from the values in an existing map

*爱你&永不变心* 提交于 2019-12-30 15:02:07

问题


Having the next original map:

G1=[7,8,45,6,9]
G2=[3,9,34,2,1,65]
G3=[6,5,9,1,67,5]

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.

I have tried this:

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())

Any help with this will be appreciated.


回答1:


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));

note the e -> Collections.max(e.getValue()).

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()));


来源:https://stackoverflow.com/questions/53861201/how-create-a-new-map-from-the-values-in-an-existing-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!