我有HashMap
这样的定义......
HashMap<String,Integer> uniqueNames = new HashMap<String,Integer>();
它存储名称和该名称的出现。例如......
uniqueNames.put("lastname",42);
如何获得出现次数最多的名称?
有关更多信息,我正在使用“人物”的二叉搜索树,将唯一的名称和频率存储在HashMap
中。我想要做的是打印最常见的姓氏,有人告诉我使用HashMap
,因为我想将String
与Integer
一起存储。也许我应该使用一个类来存储名称和频率?有人可以提供一些建议。
答案 0 :(得分:15)
如果你必须使用HashMap,那么最简单的方法可能就是遍历Map寻找最大值
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,
答案 1 :(得分:2)
最明显的是,现在允许具有最大出现值的多个:
Integer largestVal = null;
List<Entry<String, Integer>> largestList = new ArrayList<Entry<String, Integer>>();
for (Entry<String, Integer> i : uniqueNames.entrySet()){
if (largestVal == null || largestVal < i.getValue()){
largestVal = i.getValue();
largestList .clear();
largestList .add(i);
}else if (largestVal == i.getValue()){
largestList .add(i);
}
}
另一种选择是使用Guava的BiMap。
BiMap<String, Integer> uniqueNames = ...;
List<Integer> values = Lists.newArrayList(uniqueNames.values());
Collections.sort(values);
String name = uniqueNames.inverse().get(values.get(0));
答案 2 :(得分:1)
实际上有两种方法可以解决这个问题。
如果您要经常这样做,我实际上建议反向存储映射,其中键是名称出现的次数,值是多次出现的名称列表。我也会使用HashMap在另一个方向上执行查找。
TreeMap <Integer, ArrayList <String>> sortedOccurrenceMap =
new TreeMap <Integer, ArrayList <String>> ();
HashMap <String, Integer> lastNames = new HashMap <String, Integer> ();
boolean insertIntoMap(String key) {
if (lastNames.containsKey(key)) {
int count = lastNames.get(key);
lastNames.put(key, count + 1);
//definitely in the other map
ArrayList <String> names = sortedOccurrenceMap.get(count);
names.remove(key);
if(!sortedOccurrenceMap.contains(count+1))
sortedOccurrenceMap.put(count+1, new ArrayList<String>());
sortedOccurrenceMap.get(count+1).add(key);
}
else {
lastNames.put(key, 1);
if(!sortedOccurrenceMap.contains(1))
sortedOccurrenceMap.put(1, new ArrayList<String>());
sortedOccurrenceMap.get(1).add(key);
}
}
类似于删除......
最后,为了您的搜索:
ArrayList <String> maxOccurrences() {
return sortedOccurrenceMap.pollLastEntry().getValue();
}
返回具有最大出现次数的名称列表。
如果你这样做,搜索可以在O(log n)中完成,但空间需求会增加(尽管只是一个常数因素)。
如果空间有问题,或者性能不是问题,只需遍历uniqueNames.keySet并跟踪最大值。
答案 3 :(得分:0)
好像你想要的东西有点像SortedMap
,但是一个按照值排序,而不是键。我不认为标准API中存在这样的东西。
最好创建一个Frequency类并将实例存储在SortedSet
中。
import java.util.Set;
import java.util.TreeSet;
public class Frequency implements Comparable<Frequency> {
private String name;
private int freq;
public Frequency(String name, int freq) {
this.name = name;
this.freq = freq;
}
public static void main(String[] args) {
Set<Frequency> set = new TreeSet<Frequency>();
set.add(new Frequency("fred", 1));
set.add(new Frequency("bob", 5));
set.add(new Frequency("jim", 10));
set.add(new Frequency("bert", 4));
set.add(new Frequency("art", 3));
set.add(new Frequency("homer", 5));
for (Frequency f : set) {
System.out.println(f);
}
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o.getClass().isAssignableFrom(Frequency.class)) {
Frequency other = (Frequency)o;
return other.freq == this.freq && other.name.equals(this.name);
} else {
return false;
}
}
@Override
public int compareTo(Frequency other) {
if (freq == other.freq) {
return name.compareTo(other.name);
} else {
return freq - other.freq;
}
}
@Override
public String toString() {
return name + ":" + freq;
}
}
输出:
fred的:1个
技术:3
BERT:4
鲍勃:5
本垒打:5
吉姆:10
答案 4 :(得分:0)
CatchAllHandlers
答案 5 :(得分:0)
如果你只想要这个价值,你可以为此而努力。在这个例子中,我必须得到 &#39; n&#39;数组中数字的最大频率。编号
{
int n = sc.nextInt();
int arr[] = new int[n];
int freq = 1;
int i;
Map<Integer,Integer> myMap = new HashMap<Integer,Integer>();
for(i=0;i<n;i++){
arr[i] = sc.nextInt();
if(!myMap.containsKey(arr[i])){
myMap.put(arr[i],freq);
}
else
{
myMap.put(arr[i],(myMap.get(arr[i])+1));
}
}
int max = 0;
for(i=0;i<n;i++){
if(myMap.get(arr[i])>max)
max = myMap.get(arr[i]);
}
System.out.println(max);
}
答案 6 :(得分:0)
这是我的方法。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class FindWordCounter {
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter the sentence: ");
String sentence = bufferedReader.readLine();
FindWordCounter.countWord(sentence);
} catch (IOException e) {
System.out.println(e);
}
}
public static void countWord(String sentence) {
Map<String, Integer> hashMap = new HashMap<String, Integer>();
String[] word = sentence.toLowerCase().split(" ");
for (int i=0; i<word.length; i++) {
if (hashMap.containsKey(word[i])) {
int count = hashMap.get(word[i]);
hashMap.put(word[i], count + 1);
}
else {
hashMap.put(word[i], 1);
}
}
Entry<String,Integer> maxCount = null;
for(Entry<String,Integer> entry : hashMap.entrySet()) {
if (maxCount == null || entry.getValue() > maxCount.getValue()) {
maxCount = entry;
}
}
System.out.println("The word with maximum occurence is: " + maxCount.getKey()
+ " and the number of occurence is: " + maxCount.getValue());
}
}
答案 7 :(得分:0)
1。尝试此操作可能会有所帮助。
static <K, V> List<K> getAllKeysForValue(Map<K, V> mapOfWords, V value)
{
List<K> listOfKeys = null;
//Check if Map contains the given value
if(mapOfWords.containsValue(value))
{
// Create an Empty List
listOfKeys = new ArrayList<>();
// Iterate over each entry of map using entrySet
for (Map.Entry<K, V> entry : mapOfWords.entrySet())
{
// Check if value matches with given value
if (entry.getValue().equals(value))
{
// Store the key from entry to the list
listOfKeys.add(entry.getKey());
}
}
}
// Return the list of keys whose value matches with given value.
return listOfKeys;
}