如何在HashMap中发现哪个值最多?

时间:2013-11-24 10:49:08

标签: java string map hashmap

Map<String,String> votes = new HashMap<String,String>
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");

如何检索上面HashMap中出现的最多值,在这种情况下将是“School”。我将非常感谢最有效和最明确的方法。

6 个答案:

答案 0 :(得分:3)

一种解决方案是:

  • 构建一个具有字符串 HashMapkey值的新int
  • 对于当前value的每个HashMap
    • 在新key中添加HashMap值,如果是第一次插入则值为1。
    • 否则,请将当前value的{​​{1}}增加一个。
  • 现在迭代新创建的地图并检索具有最大密钥

对于您当前的地图:

key

您将首先插入votes.put("Henk","School"); votes.put("Elise","School"); votes.put("Jan","Work"); votes.put("Mert","Party"); 作为键,值为1.然后再次面对School,因此您将增加1,计数为2.现在您插入带有 1的School和带有值1的Work

在地图上进行迭代后,您将获得具有最高Party。这就是你想要的!

答案 1 :(得分:3)

更简单的解决方案是查看值。

public static <E> E mostFrequentElement(Iterable<E> iterable) {
    Map<E, Integer> freqMap = new HashMap<>();
    E mostFreq = null;
    int mostFreqCount = -1;
    for (E e : iterable) {
        Integer count = freqMap.get(e);
        freqMap.put(e, count = (count == null ? 1 : count+1));
        // maintain the most frequent in a single pass.
        if (count > mostFreqCount) {
            mostFreq = e;
            mostFreqCount = count;
        }
    }
    return mostFreq;
}

和你可以做的地图

V v = mostFrequentElement(map.values());

答案 2 :(得分:2)

只需使用API​​:

        Map<String,String> votes = new HashMap<String,String>();
        votes.put("Henk","School");
        votes.put("Elise","School");
        votes.put("Jan","Work");
        votes.put("Mert","Party");

        Collection<String> c = votes.values();
        List<String> l = new ArrayList<>(c);

        Set<String> set = new HashSet<>(c);
        Iterator<String> i = set.iterator();
        String valueMax = "";
        int max = 0;
        while(i.hasNext()){
            String s = i.next();
            int frequence = Collections.frequency(l, s);
            if(frequence > max){
                max = frequence;
                valueMax = s;
            }
        }

        System.out.println(valueMax+": "+max);

输出:

School: 2

答案 3 :(得分:0)

我相信这会做你想要的 -

/**
 * Get the most frequent value present in a map.
 * 
 * @param map
 *          The map to search.
 * @return The most frequent value in the map (or null).
 */
public static <K, V> V getMostFrequentValue(
    Map<K, V> map) {
  // Make sure we have an entry.
  if (map != null && map.size() > 0) {
    // the entryset from our input.
    Set<Entry<K, V>> entries = map.entrySet();

    // we need a map to hold the count.
    Map<V, Integer> countMap = new HashMap<V, Integer>();
    // iterate the entries.
    for (Entry<K, V> entry : entries) {
      // get the value.
      V value = entry.getValue();

      if (countMap.containsKey(value)) {
        // if we've seen it before increment the previous
        // value.
        countMap.put(value, countMap.get(value) + 1);
      } else {
        // otherwise, store 1.
        countMap.put(value, 1);
      }
    }
    // A holder for the maximum.
    V maxV = null;
    for (Entry<V, Integer> count : countMap.entrySet()) {
      if (maxV == null) {
        maxV = count.getKey();
        continue;
      }
      if (count.getValue() > countMap.get(maxV)) {
        maxV = count.getKey();
      }
    }
    return maxV;
  }
  return null;
}

答案 4 :(得分:0)

这是Maroun伪代码的实现。尝试,

   Map<String, String> votes = new HashMap<String, String>();
    votes.put("Henk", "School");
    votes.put("Elise", "School");
    votes.put("Jan", "Work");
    votes.put("Mert", "Party");
    //Define a countMap with String as value, Integer for count
    Map<String, Integer> countMap = new HashMap<>();

    for (Map.Entry<String, String> entry : votes.entrySet()) {
        if (countMap.containsKey(entry.getValue())) {
            countMap.put(entry.getValue(), countMap.get(entry.getValue()) + 1);
        } else {
            countMap.put(entry.getValue(), 1);
        }
    }
    // Got the number of maximum occuarance
   Integer maxNum = Collections.max(countMap.values());

    String result = "";
     // Iterate to search the result.
    for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
        if(maxNum==entry.getValue()){
            result=entry.getKey();
        }

    }
    System.out.println(result);

答案 5 :(得分:0)

您可以覆盖put()类的remove()HashMap,并创建自定义的类,同时控制添加的对象数量。像这样:

public class MyHashMap<K, V> extends HashMap<K, V> {

private HashMap<String, Integer> countMap = new HashMap<String, Integer>();

@Override
public V put(K key, V value) {
    Integer count = countMap.get(value);
    if (count != null) {
        countMap.put((String) value, ++count);
    } else {
        countMap.put((String) value, new Integer(1));
    }


    return super.put(key, value);
}

@Override
public V remove(Object key) {
    String countKey = (String) get(key);
    Integer  count = countMap.get(countKey);
    if (count != null) {
        countMap.put(countKey, --count);
    }

    return super.remove(key);
}

public Integer getCount(Object value) {
    return countMap.get((String)value);
}

}

这样您就不必遍历HashMap的元素来计算它们。而是在添加它们之后:

Map<String,String> votes = new MyHashMap<String,String>
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");

你可以得到每个的计数:

Integer schoolCount = votes.getCount("School");