从哈希图中获取具有最大值的键? [英] Get the keys with the biggest values from a hashmap?

查看:38
本文介绍了从哈希图中获取具有最大值的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样定义的 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?

有关更多信息,我正在使用人"的二叉搜索树,将唯一名称和频率存储在 HashMap 中.我想做的是打印最常见的姓氏,有人告诉我使用 HashMap 因为我想将 StringInteger<一起存储/代码>.也许我应该使用一个类来存储名称和频率?有人可以提供一些建议吗?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆