Warm tip: This article is reproduced from serverfault.com, please click

Finding the key corresponding to the maximum value in a hash map

发布于 2020-11-29 21:22:29

I'm trying to find the key corresponding to the maximum value in a HashMap. My declaration is as follows:

HashMap<Node, Double> coinD= new HashMap<>();

However, when I try to use an anonymous function to compare two values inside the entrySet of this map, I get a type casting error:

Node bestNode = Collections.max(coinD.entrySet(), (e1, e2) -> e1.getValue() - e2.getValue()).getKey();

Returns a type mismatch on e1.getValue() and e2.getValue(): cannot convert from double to int. Where is this coming from? Why is an integer necessary here; why can't the function use doubles to compare? Does the function I defined require ints, or does .getValue() have to return an int? Any help would be greatly appreciated!

Questioner
rjc810
Viewed
0
tucuxi 2020-11-30 05:43:56

You are attempting to pass a lambda that should implement Comparable as an argument to max, but Comparable must return an int, while you are producing a double as the result of subtracting a double from another.

You can fix this easily by using Double.compare(e1.getValue(), e2.getValue()) instead of subtracting both values:

 Node bestNode = Collections.max(coinD.entrySet(), 
        (e1, e2) -> Double.compare(e1.getValue(), e2.getValue())).getKey();

@ernest_k also has a good point: if the values of your map are have a natural sort order, and you want to use that order, Map.Entry.comparingByValue yields slightly shorter code:

 Node bestNode = Collections.max(coinD.entrySet(), 
        (e1, e2) -> Map.Entry.comparingByValue()).getKey();