+ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
+ return sortByValue(map, false);
+ }
+
+ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean descending) {
+ List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
+ list.sort(Entry.comparingByValue());
+ if (descending)
+ Collections.reverse(list);
+
+ Map<K, V> result = new LinkedHashMap<>();
+ for (Entry<K, V> entry : list) {
+ result.put(entry.getKey(), entry.getValue());
+ }
+
+ return result;
+ }
+