map集合根据value值排序

public class MapSortedDemo {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put(1, "22");
map.put(2, "able");
map.put(3, "disk");
map.put(4, "banana");
map.put(5, "001");
sortMap(map);
}

/**
* map 集合根据value值排序
*
* @param map
* @return
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortMap(Map map) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
list.sort((o1, o2) -> {
// 按照 value进行排序
// return (o2.getValue()).compareTo(o1.getValue()); // 20 ,3,1 倒叙
return (o1.getValue()).compareTo(o2.getValue()); // 1 ,3,20 正序
// 按照key 进行排序
// return ((String) o1.getKey()).compareTo((String) o2.getKey()); // k1 ,k2,k3 正序
// return ((String) o2.getKey()).compareTo((String) o1.getKey()); // k3 ,k2,k1 倒叙
});

Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
System.out.println("result = " + result);
return result;
}
}
运行:
result = {5=001, 1=22, 2=able, 4=banana, 3=disk}
不积跬步,无以至千里;不积小流,无以成江海。
原文地址:https://www.cnblogs.com/d0minic/p/14072228.html