1

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!

rjc810
  • 425
  • 1
  • 3
  • 17
  • 2
    If your values are `Double`-typed, you can't use `d1-d2` because that returns a `double` which is not compatible with the `int` return type of `Comparator.compare`. Try `.max(coinD.entrySet(), Map.Entry.comparingByValue())` or `.max(coinD.entrySet(), (e1,e2)->Double.compare(e1,e2))` – ernest_k Nov 29 '20 at 21:28

1 Answers1

3

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();
tucuxi
  • 17,561
  • 2
  • 43
  • 74
  • Thanks for the answer- just to clarify, what would a "natural sort order" constitute? – rjc810 Nov 29 '20 at 21:54
  • 2
    @rjc810 - take a look at [What is natural ordering when we talk about sorting?](https://stackoverflow.com/questions/5167928/what-is-natural-ordering-when-we-talk-about-sorting) - that may help. – andrewJames Nov 29 '20 at 21:58