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

前端 未结 1 1363
忘了有多久
忘了有多久 2021-01-17 06:24

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 ca

1条回答
  •  佛祖请我去吃肉
    2021-01-17 06:39

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

    0 讨论(0)
提交回复
热议问题