首页 > 解决方案 > 在哈希映射中找到最大值对应的键

问题描述

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

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

但是,当我尝试使用匿名函数来比较此映射的 entrySet 内的两个值时,我得到一个类型转换错误:

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

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

标签: javahashmapmax

解决方案


您正在尝试传递一个 lambda,该 lambda 应该实现Comparable作为参数max,但Comparable 必须返回一个int,而您正在生成 adouble作为从另一个中减去双精度的结果。

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

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

@ernest_k也有一个好处:如果您的地图的值具有自然排序顺序,并且您想使用该顺序,则Map.Entry.comparingByValue会产生略短的代码:

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

推荐阅读