Obtaining key associated with corresponding maximum value in a Map(TreeMap/HashMap)

久未见 提交于 2019-12-02 02:16:17

The trick is that you can find maximum value together with its key by providing Comparator that compares entries by value.

Comparator<Map.Entry<String, Integer>> byValue = Map.Entry.comparingByValue();
Map.Entry<String, Integer> maxEntry = Collections.max(map.entrySet(), byValue);
System.out.println("Maximum value is " + maxEntry.getValue());
System.out.println("And it is for " + maxEntry.getKey());

Or using new stream API

map.entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .ifPresent(maxEntry -> {
        System.out.println("Maximum value is " + maxEntry.getValue());
        System.out.println("And it is for " + maxEntry.getKey());
    });

You seem to be asking if using TreeMap instead of HashMap will give you a simpler way to find the key corresponding to the largest value/

The answer to that is ... unfortunately ... No.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!