如果我想让一个Map<Key, Value>根据Value进行排序,该怎么做?有没有什么简单一点的方法。
首先提一下Map的几个主要的实现类,HashMap、TreeMap和LinkedHashMap在存储顺序上的差异。
为了保持排序,我们使用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;
}
方法二,使用stream接口。
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
return map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue, (e1, e2) -> e1,
LinkedHashMap::new
));
}
内容