java基础之转换map排序

1、key排序

    /**
     * 使用 Map按key进行排序
     *
     * @param unSortMap
     * @return
     */
    public static Map<String, String> SortByKey(Map<String, String> unSortMap) {
        Map<String, String> result = unSortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        return result;
    }

2、value排序

    /**
     * 使用 Map按value进行排序
     *
     * @param unSortMap
     * @return
     */
    public static Map<String, String> sortByValueDesc(Map<String, String> unSortMap) {
        Map<String, String> result = unSortMap.entrySet().stream()
                .sorted(Map.Entry.<String, String>comparingByValue().reversed())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        return result;
    }

    public static Map<String, String> sortByValueAsc(Map<String, String> unSortMap) {
        Map<String, String> result = unSortMap.entrySet().stream()
                .sorted(Map.Entry.<String, String>comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        return result;
    }
发布了49 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/csdnzhang365/article/details/95353553