java - 在哈希映射中找到最大值对应的键
问题描述
我正在尝试找到与 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() 是否必须返回一个整数?任何帮助将不胜感激!
解决方案
您正在尝试传递一个 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();
推荐阅读
- symfony - Symfony Twig 中的优化引导进度条
- python - scapy "TypeError: 'IP' 对象不可调用"
- javascript - 过渡在第一次创建图表时不起作用
- javascript - Ionic 3 - 手动触发模糊事件
- bash - 无法获取分配给变量的多个命令(由 PIPE 分隔)的退出状态
- vue.js - vue js mutli vselect不允许从下拉列表中重复选择
- c# - 可以用空值初始化 WeakReference 吗?
- android - 在 Kotlin 中,一个 Handler 线程会等待另一个线程完成吗?
- graphql - 使用 GraphQL 进行微服务互通有意义吗?
- c++ - VC++ wcsftime (strftime) 不返回带有 %x 的正确语言环境字符串