简体   繁体   English

java Hashmap:获取具有最大数量的值的键

[英]java Hashmap : Get the key with maximum number of values

I am trying to get the key with maximum number of values (not max value). 我正在尝试获取具有最大数量的值(而不是最大值)的钥匙。 I ave tried a couple of thing like counting values iterating over each key. 我尝试了几件事,例如计算对每个键进行迭代的值。 But they boil down to problem finding a key from value which is problematic when we have same values. 但是他们归结为从价值中寻找钥匙的问题,当我们拥有相同的价值时,这是有问题的。

    // calculate the length
    for(String key : map.keySet())
    {

        len.add(map.get(key).size());

    }

    // sort the length
    Collections.sort(len, Collections.reverseOrder() );

If you're using Java 8, this could just be 如果您使用的是Java 8,则可能只是

String maxKey = map.entrySet().stream()
  .max(Comparator.comparingInt(entry -> entry.getValue().size()))
  .get().getKey();

if not, I'd tend to write this as 如果没有,我倾向于写成

String maxKey = Collections.max(map.entrySet(), 
   new Comparator<Map.Entry<String, List<Value>>>() {
      @Override public int compare(
          Map.Entry<String, List<Value>> e1, Map.Entry<String, List<Value>> e2) {
        return Integer.compare(e1.getValue().size(), e2.getValue().size());
      }
   }).getKey();

...or, you could just write ...或者,你可以写

String maxKey = null;
int maxCount = 0;
for (Map.Entry<String, List<Value>> entry : map.entrySet()) {
  if (entry.getValue().size() > maxCount) {
    maxKey = entry.getKey();
    maxCount = entry.getValue().size();
  }
}
return maxKey;
String maxKey = null;
for (String key : map.keySet())
{
    if (maxKey == null || map.get(key).size() > map.get(maxKey).size())
    {
        maxKey = key;
    }
}

This would be my solution to the problem. 这将是我解决问题的方法。 After execution, maxKey is key with the most values. 执行后, maxKey是具有最多值的键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM