Map根据value值排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/System_out_print_Boy/article/details/84647412

Map的key是机场名字,value 是流量。根据流量倒序排序

/**
     * 使用 Map按value进行排序
     * @param map
     * @return
     */
    public static Map<String, Integer> sortMapByValue(Map<String, Integer> oriMap) {
        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;
    }
   public static class MapValueComparator implements Comparator<Map.Entry<String, Integer>> {

        @Override
        public int compare(Entry<String, Integer> me1, Entry<String, Integer> me2) {
            //按照从大到小的顺序排列,如果想正序 调换me1 me2的位置
            return me2.getValue().compareTo(me1.getValue());
        }
    }

猜你喜欢

转载自blog.csdn.net/System_out_print_Boy/article/details/84647412