java版本1.8之前可以使用这个,利用list存储map,然后利用map.entry中自带的比较器比较。最后存入LinkedHashMap
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue());
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
java版本1.8及以上的,可以直接利用流处理。需要注意的是最后需要用forEachOrdered遍历,而不能用forEach遍历,forEach是保证效率,但是不保证输出的顺序的。
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue2(Map<K, V> map) {
LinkedHashMap<K,V> result =new LinkedHashMap<>();
map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEachOrdered(x->result.put(x.getKey(),x.getValue()));
return result;
}