Get the keys with the biggest values from a hashmap?

后端 未结 8 1713
时光取名叫无心
时光取名叫无心 2020-12-06 02:01

I have a HashMap defined like this...

HashMap uniqueNames = new HashMap();

It stor

8条回答
  •  爱一瞬间的悲伤
    2020-12-06 02:33

    Most obvious, now allowing for multiple with largest occurrence value:

    Integer largestVal = null;
    List> largestList = new ArrayList>();
    for (Entry i : uniqueNames.entrySet()){
         if (largestVal == null || largestVal  < i.getValue()){
             largestVal = i.getValue();
             largestList .clear();
             largestList .add(i);
         }else if (largestVal == i.getValue()){
             largestList .add(i);
         }
    }
    

    Another option would be to use Guava's BiMap.

    BiMap uniqueNames = ...;
    List values = Lists.newArrayList(uniqueNames.values());
    Collections.sort(values);
    String name = uniqueNames.inverse().get(values.get(0));
    

提交回复
热议问题