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:小五

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM