public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean asc)
{
Map<K, V> result = new LinkedHashMap<>();
Stream<Map.Entry<K, V>> stream = map.entrySet().stream();
if (asc) //升序
{
//stream.sorted(Comparator.comparing(e -> e.getValue()))
stream.sorted(Map.Entry.<K, V>comparingByValue())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
else //降序
{
//stream.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
stream.sorted(Map.Entry.<K, V>comparingByValue().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
public static <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map, boolean asc)
{
Map<K, V> result = new LinkedHashMap<>();
Stream<Map.Entry<K, V>> stream = map.entrySet().stream();
if (asc)
{
stream.sorted(Map.Entry.<K, V>comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
else
{
stream.sorted(Map.Entry.<K, V>comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
网友评论