/** * Map通过key进行排序 * @param map * @param isDesc * @param <K> * @param <V> * @return */ public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean isDesc) { Map<K, V> result = new LinkedHashMap<>(); if (isDesc) { map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed()) .forEachOrdered(e -> result.put(e.getKey(), e.getValue())); } else { map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey()) .forEachOrdered(e -> result.put(e.getKey(), e.getValue())); } return result; }
把 "map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())" 里面的
comparingByKey()换成comparingByValue() 就是根据 value 来排序
---带文字的字符串可以识别,底层实现原理没研究.(有机会要理一理)