Java Map 中取最大与最小 Value 对应的Key值

Java Map 中取最大与最小 Value 对应的Key值

public class MaxMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap();
        map.put("张三", 5);
        map.put("小三", 0);
        map.put("小四", 3);
        map.put("小五", 9);
        map.put("李四", 2);
        map.put("王五", 1);

        List<Map.Entry<String, Integer>> list = new ArrayList(map.entrySet());
        Collections.sort(list, (o1, o2) -> (o1.getValue().intValue() - o2.getValue().intValue()));
        String min = list.get(0).getKey();
        String max = list.get(list.size() - 1).getKey();

        System.out.println("最小的Key:" + min);
        System.out.println("最大的Key:" + max);
    }

}

输出结果:

最小的Key:小三
最大的Key:小五

 

posted @ 2021-12-09 19:53  不经意的瞬间  阅读(2618)  评论(0编辑  收藏  举报