在哈希映射中查找与最大值对应的键

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

我试图在 HashMap 中找到对应于最大值的键。我的声明如下:

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

但是,当我尝试使用匿名函数比较此映射的 entrySet 中的两个值时,出现类型转换错误:

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

Returns e1.getValue() 和 e2.getValue() 上的类型不匹配:无法从 double 转换为 int。这是从哪里来的?为什么这里需要一个整数;为什么函数不能使用双打来比较?我定义的函数是否需要整数,或者 .getValue() 是否必须 return 一个整数?任何帮助将不胜感激!

您正在尝试将应实现 Comparable 的 lambda 作为参数传递给 max,但是 Comparable 必须 return 一个 int,而你正在生成一个 double 作为从另一个减去双精度的结果。

您可以使用 Double.compare(e1.getValue(), e2.getValue()) 而不是同时减去两个值来轻松解决此问题:

 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 生成的代码略短:

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