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?
有关更多信息,我正在使用人"的二叉搜索树,将唯一名称和频率存储在 HashMap 中.我想做的是打印最常见的姓氏,有人告诉我使用 HashMap 因为我想将 String 与 Integer<一起存储/代码>.也许我应该使用一个类来存储名称和频率?有人可以提供一些建议吗?
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,
这篇关于从哈希图中获取具有最大值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从哈希图中获取具有最大值的键?
基础教程推荐
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 将 Windows 证书导入 Java 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
