Warm tip: This article is reproduced from serverfault.com, please click

java-在哈希图中查找与最大值对应的键

(java - Finding the key corresponding to the maximum value in a hash map)

发布于 2020-11-29 21:22:29

我想在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。这是哪里来的?为什么这里需要整数?为什么函数不能使用双精度进行比较?我定义的函数需要int还是.getValue()必须返回int?任何帮助将不胜感激!

Questioner
rjc810
Viewed
0
tucuxi 2020-11-30 05:43:56

你尝试将应实现Comparable的lambda作为参数传递给max,但在生成a时却Comparable 返回一个int,这是double因为从另一个中减去了double的结果。

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

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

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

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