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() );
Cœur
  • 37,241
  • 25
  • 195
  • 267
maddie
  • 629
  • 10
  • 29
  • What version of Java are you using? If it's Java 8, it's a lot easier. – Louis Wasserman Dec 04 '15 at 22:11
  • Possible duplicate answer [http://stackoverflow.com/questions/5911174/finding-key-associated-with-max-value-in-a-java-map](http://stackoverflow.com/questions/5911174/finding-key-associated-with-max-value-in-a-java-map) – Abdelhak Dec 04 '15 at 22:17
  • for Map, each key can map to at most one value. Number of values for all keys will be either 0 or 1. – Eldar Budagov Dec 04 '15 at 22:23

2 Answers2

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;
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
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.

Jan Dörrenhaus
  • 6,581
  • 2
  • 34
  • 45
  • Thanks @Jan Works like a charm. I was over complicating it by using so many unnecessary data structures. – maddie Dec 04 '15 at 23:40