简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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