Java 根據value對Map進行排序得到最大值

import java.util.*;

public class treeMap {
    static String key1 ="";
    static Integer vlue1 ;
    public static void main(String [] arg){

        Map<String,Integer> map = new TreeMap<>();
        map.put("1",2);
        map.put("2",4);
        map.put("3",5);
        map.put("4",12);
        map.put("5",23);
        map.put("6",65);
        map.put("7",1);
        map.put("8",10);
       Map<String , Integer> map1 = new HashMap<>();
        map1 = sortMapByValue(map);
        for (String key : map1.keySet()) {
            key1 =key;
            vlue1=map1.get(key);
            System.out.println("key= "+ key + " and value= " + map1.get(key));
        }
        System.out.println("方位號:"+key1+"\n 距離:"+vlue1);

    }


    public static Map<String, Integer> sortMapByValue(Map<String, Integer> oriMap) {
         class MapValueComparator implements Comparator<Map.Entry<String, Integer>> {

            @Override
            public int compare(Map.Entry<String, Integer> me1, Map.Entry<String, Integer> me2) {

                return me1.getValue().compareTo(me2.getValue());
            }
        }
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(
                oriMap.entrySet());
        Collections.sort(entryList, new MapValueComparator());

        Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
        Map.Entry<String, Integer> tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章