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!
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();
Thanks for the answer- just to clarify, what would a "natural sort order" constitute?
@rjc810 - take a look at What is natural ordering when we talk about sorting? - that may help.