从哈希图中获取具有最大值的键?

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 因为我想将 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,

这篇关于从哈希图中获取具有最大值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)