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

问题描述 投票:0回答:8

我有一个像这样定义的

HashMap
...

HashMap<String,Integer> uniqueNames = new HashMap<String,Integer>();

它存储一个名称以及该名称的出现情况。例如...

uniqueNames.put("lastname",42);

如何获取出现次数最多的名字?

有关更多信息,我正在使用“人”的二叉搜索树,将唯一的名称和频率存储在

HashMap
中。我想做的是打印最常见的姓氏,有人告诉我使用
HashMap
,因为我想将
String
Integer
一起存储。也许我应该使用一个类来存储名称和频率?有人可以提供一些建议吗?

java hashmap
8个回答
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,

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));

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 并跟踪最大值即可。


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;
  }

}

输出:

弗雷德:1
艺术:3
伯特:4
鲍勃:5
本垒打:5
吉姆:10


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());
}

}

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;  
}

0
投票
List<String> list= new ArrayList<String>();
HashMap<String, Integer> map=new HashMap<String,Integer>();

for(String string: list)
{
 if(map.containsKey(string))
 {
     map.put(string, map.get(string)+1);
 }
 else {
    map.put(string, 1);
}
}


Entry<String,Integer> maxEntry = null;

for(Entry<String,Integer> entry : map.entrySet()) {
    if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
        maxEntry = entry;
    }
}

0
投票

如果你只想要价值,你可以选择这个。在这个例子中我必须得到 “n”个数字数组中某个数字的最大频率

 {
   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);
}
© www.soinside.com 2019 - 2024. All rights reserved.