1

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

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

1
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.

1 Comment

Thanks @Jan Works like a charm. I was over complicating it by using so many unnecessary data structures.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.