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

发布于 2024-12-05 17:21:16 字数 470 浏览 0 评论 0原文

我有一个像这样定义的 HashMap...

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

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

uniqueNames.put("lastname",42);

我怎样才能得到出现次数最多的名字?

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

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?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

错爱 2024-12-12 17:21:16

如果必须使用 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,

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,
忆离笙 2024-12-12 17:21:16

最明显的是,现在允许具有最大出现值的多个:

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

Most obvious, now allowing for multiple with largest occurrence value:

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

Another option would be to use Guava's BiMap.

BiMap<String, Integer> uniqueNames = ...;
List<Integer> values = Lists.newArrayList(uniqueNames.values());
Collections.sort(values);
String name = uniqueNames.inverse().get(values.get(0));
相对绾红妆 2024-12-12 17:21:16

实际上有两种方法可以解决这个问题。

如果您要经常这样做,我实际上建议反向存储映射,其中键是名称出现的次数,值是出现多次的名称列表。我还会使用 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 并跟踪最大值。

There are two ways of going about this actually.

If you are going to be doing this frequently, I would actually suggest storing the mapping in reverse, where the key is the number of times a name has appeared, and the value is a list of names which appeared that many times. I would also use a HashMap to perform the lookups in the other direction as well.

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

Something similar for deleting...

And finally, for your search:

ArrayList <String> maxOccurrences() {
    return sortedOccurrenceMap.pollLastEntry().getValue();
}

Returns the List of names that have the max occurrences.

If you do it this way, the searching can be done in O(log n) but the space requirements increase (only by a constant factor though).

If space is an issue, or performance isn't a problem, simply iterate through the uniqueNames.keySet and keep track of the max.

夜清冷一曲。 2024-12-12 17:21:16

似乎您想要一些类似于 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

Seems like you want something a bit like a SortedMap but one sorted on the value, not the key. I don't think such a thing exists in the standard API.

It might be better to create a Frequency class and store instances in a SortedSet instead.

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

}

Output:

fred:1
art:3
bert:4
bob:5
homer:5
jim:10

深海夜未眠 2024-12-12 17:21:16

这是我的方法。

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

}

This is my approach.

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

}
九局 2024-12-12 17:21:16

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

1.Try this it may help.

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;  
}
ゝ偶尔ゞ 2024-12-12 17:21:16
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;
    }
}
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;
    }
}
ι不睡觉的鱼゛ 2024-12-12 17:21:16

如果你只想要价值,你可以选择这个。在这个例子中我必须得到
“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);
}

If you only want the value you can go for this. In this example I had to get the
maximum frequency of a number among an array of 'n' numbers

 {
   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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文