美文网首页
java8 map排序 按key 和value两种方式

java8 map排序 按key 和value两种方式

作者: wsj1211 | 来源:发表于2019-08-24 14:27 被阅读0次

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;
}

相关文章

网友评论

      本文标题:java8 map排序 按key 和value两种方式

      本文链接:https://www.haomeiwen.com/subject/hxqqectx.html