Map排序

1.以key排序

/**
    * @Description 主要依赖java8 map流处理中 comparingByKey 函数, 根据 map  key做排序
    * @Description 本质是建立一个List<Map<k,v>>容器,将map遍历比较后,放入有序map集合
    * @Description 由于comparing 实际使用的是 compareTo 函数,所以当以key为排序字段时,key必须为String
    * @Param Map<Object, String>
    * @Param isDesc 是否降序,true:降序,false:升序
    * @Return 返回一个LinkedHashMap
    */
    public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean isDesc) {
        Map<K, V> result ;
        if (isDesc) {
            result = map.entrySet().stream()
                    .sorted(Map.Entry.<K, V>comparingByKey().reversed())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        } else {
            result = map.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        }
        return result;
    }

2.以value排序

/**
     * @Description 主要依赖java8 map流处理中 comparingByValue 函数, 根据 map  value做排序
     * @Description 本质是建立一个List<Map<k,v>>容器,将map遍历比较后,放入有序map集合
     * @Description 由于comparing 实际使用的是 compareTo 函数,所以当以Value为排序字段时,Value必须为String
     * @Param Map<Object, String>
     * @Param isDesc 是否降序,true:降序,false:升序
     * @Return 返回一个LinkedHashMap
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean isDesc) {
        Map<K, V> result ;
        if (isDesc) {
            result = map.entrySet().stream()
                    .sorted(Map.Entry.<K, V>comparingByValue().reversed())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        } else {
            result = map.entrySet().stream()
                    .sorted(Map.Entry.comparingByValue())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        }
        return result;
    }

 

 

3.好的帖子:

https://www.cnblogs.com/li150dan/p/11135285.html

https://blog.csdn.net/xiakexiaohu/article/details/85174132

不是很明白为什么大家不建议.forEachOrdered输出,看起来代码量更简洁啊。

难道是因为使用了有序循环影响了输出速度吗?

posted @ 2020-08-01 20:27  冬凛  阅读(274)  评论(0)    收藏  举报