Java Map 中獲取最大值 Value 和對應的 Key


Java Map 中獲取最大值 Value 和對應的 Key

案例如下

import java.util.*;

public class MaxMapDemo {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap();
        map.put("張三", 28);
        map.put("李四", 18);
        map.put("王五", 8);
        System.out.println("Map中Value(值)的最大值的Key:" + getMaxStr(map));
    }

    public static String getMaxStr(Map<String, Object> map) {
        int maxV = 0;
        String maxK = null;
        //臨時值,保存每次最大值鍵,下個值比他大就將他替掉,換成新值
        String maxKRemove = null;
        Map<String, Object> map2 = new TreeMap();
        Iterator keys = map.keySet().iterator();
        while (keys.hasNext()) {
            Object key = keys.next();
            maxK = key.toString();
            int value = Integer.parseInt(map.get(key).toString());
            if (value > maxV) {
                if (null != maxKRemove) {
                    map2.clear();
                }
                maxV = value;
                map2.put(maxK, maxV);
                maxKRemove = maxK;
            } else if (value == maxV) {
                map2.put(maxK, maxV);
            }
        }

        Iterator keys2 = map2.keySet().iterator();
        String strKey = "";
        int value = 0;
        while (keys2.hasNext()) {
            Object key = keys2.next();
            maxK = key.toString();
            value = Integer.parseInt(map.get(key).toString());
            String[] maxKey = maxK.split("_");
            strKey = maxKey[0];
        }
        System.out.println("Key:" + strKey + ",Value:" + value);
        return strKey;
    }

輸出的結果

Key:張三,Value:28
Map中Value(值)的最大值的Key:張三

 


免責聲明!

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



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