如何从HashMap中获取与最大值对应的Key?
我有以下 treemap
具有给定2个值:
Map<Integer, Integer> map = new TreeMap<>();
// 1 --> 3
// 2 --> 4
我想获得具有最大值的键。我通过以下方式获得最大值:
int max = map.values().stream().max(Integer::compare).get();
// 4
但是,我无法根据此最大值过滤地图键。那么,如何获得最大值(2)的关键?还是 treemap
中给定值的键?我使用 treemap
而不是 hashmap
,以便在需要时可以对地图进行排序(也许不需要)。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,
HashMap
就足够了,如果您不将其用于其他用途,则可以将TreeMap
替换为HashMap
。此外,TreeMap
无法帮助完成此任务,因为根据 键 维护条目的顺序,而不是基于值(您的示例稍微有点误导 - 最大值映射到最大键,如果更改它,TreeMap
将不再有帮助)。要使用 Stream API 解决此问题,首先,您需要在条目集上创建一个流,因为当您只有值时无法访问键。
终端操作
max()
返回一个可选对象,该对象将保存条目(如果结果存在)。在可选对象上调用的方法map()
会将Optional>
转换为Optional
。在这种情况下,方法
orElseThrow()
将是get()
的更好替代方法。如果可选对象为空,两者都会抛出异常。如果根据您的逻辑,保证值存在,那么最好使用orElseThrow()
显式指定您的意图是在结果不存在时抛出异常,因为这种情况是异常的。由于多个键可能具有相同的值,因此最大值可能会映射到多个键。在这种情况下,您可能想要获取这些键的列表:
Sidenote:当您使用
TreeMap
并且不希望为该变量分配未排序的值时实现接口Map
,然后使用接口NavigableMap
作为类型。它将为您提供对getFirstEntry()
、getFirstKey()
、higherEntry()
等不可用的方法的访问与地图
。For that purpose,
HashMap
will suffice, you might replaceTreeMap
with aHashMap
if you are not utilizing it for anything else. And moreover,TreeMap
can't help with this task because maintains the order of entries based on keys, not on values (your example is slightly misleading - max value is mapped to a max key, if you change it,TreeMap
will no longer be helpful).To solve this problem with Stream API, firstly, you need to create a stream over the entry set, because you can't access a key when you have only a value.
Terminal operation
max()
returns an optional object that will hold entry (if result is present). Methodmap()
invoked on an optional will transformOptional<Map.Entry<Integer, Integer>>
intoOptional<Integer>
.Method
orElseThrow()
in this case will be a better alternative toget()
. Both will throw an exception if optional object will be empty. If according to your logic, value is guaranteed to be present it better specify explicitly withorElseThrow()
that your intention is to throw an exception when result is not present, because this case is abnormal.Since multiple keys could have the same value, it is possible that max value will be mapped to more than one key. In this case you might want to get a list of these keys:
Sidenote: when you are working with a
TreeMap
and don't expect that variable could be assigned with an unsorted implementation of the interfaceMap
, then use interfaceNavigableMap
as a type. It'll provide you access to such methods asgetFirstEntry()
,getFirstKey()
,higherEntry()
, etc. that will not be available withMap
.要获得正确的密钥,您可以使用以下命令:
To get the proper key you can use this:
如果使用适当的接口,这将非常容易。
更重要的是,这比使用任何流都要高得多。
If you use the proper interface, this is extremely easy.
More importantly, this is much more efficient than using any Stream at all.