Map根據value值排序
阿新 • • 發佈:2018-11-30
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()); } }