从哈希映射中获取最大值的密钥? [英] Get the keys with the biggest values from a hashmap?
问题描述
我有一个像这样定义的 HashMap
...
I have a HashMap
defined like this...
HashMap<String,Integer> uniqueNames = new HashMap<String,Integer>();
它存储一个名称和该名称的出现。例如...
It stores a name, and the occurence of that name. For example...
uniqueNames.put("lastname",42);
如何获得名称最高的名称?
How can I get the name with the highest occurrence?
有关更多信息,我正在使用people的二叉搜索树,将唯一名称和频率存储在 HashMap
中。我想要做的是打印最常见的姓,并且有人告诉我使用 HashMap
,因为我想存储 String
和一个整数
。也许我应该使用一个类来存储名称和频率呢?有人可能会提供一些建议。
For some more information, I'm working with a binary search tree of "people", storing the unique names and frequencies in a HashMap
. What I want to do is to print the most common last names, and someone told me to use HashMap
as I wanted to store a String
together with an Integer
. Maybe I should use a class to store the name and frequency instead? Could someone please offer some suggestions.
推荐答案
如果您必须使用HashMap,那么最简单的方法可能只是循环Map查找最大值
If you have to use a HashMap, then the simplest way is probabably just to loop through the Map looking for the maximum
Entry<String,Integer> maxEntry = null;
for(Entry<String,Integer> entry : uniqueNames.entrySet()) {
if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
maxEntry = entry;
}
}
// maxEntry should now contain the maximum,
这篇关于从哈希映射中获取最大值的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!