java stream 操作map根据key或者value排序的实现

java8 使用lambda表达式和Stream APi 实现 list 集合转成map, 根据map的key 排序 和value 排序的实现
public class Test02 {
    public static void main(String[] args) {
        List<FundBenchMarkInfo> fundBenchMarkList = new ArrayList<>();
        fundBenchMarkList.add(new FundBenchMarkInfo("2", new BigDecimal("123"), null));
        fundBenchMarkList.add(new FundBenchMarkInfo("5", new BigDecimal("12"), null));
        fundBenchMarkList.add(new FundBenchMarkInfo("1", new BigDecimal("8"), null));
        fundBenchMarkList.add(new FundBenchMarkInfo("7", new BigDecimal("8"), new BigDecimal("123345")));
        fundBenchMarkList.add(new FundBenchMarkInfo("8", new BigDecimal("3"), new BigDecimal("90")));
        fundBenchMarkList.add(new FundBenchMarkInfo("8", new BigDecimal("8"), null));

        // 把list 转成 map
        Map<String, FundBenchMarkInfo> collect = fundBenchMarkList.stream().collect(Collectors.toMap(t -> t.getIndexScod(), o -> o, (k1, k2) -> k1));

        // map 根据 key 排序
        LinkedHashMap<String, FundBenchMarkInfo> collect1 = collect.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));

        Map<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("z", 10);
        unsortMap.put("b", 5);
        unsortMap.put("a", 6);
        unsortMap.put("c", 20);
        unsortMap.put("d", 1);
        unsortMap.put("e", 7);
        unsortMap.put("y", 8);
        unsortMap.put("n", 99);
        unsortMap.put("g", 50);
        unsortMap.put("m", 2);

        // 根据key 排序
        //Alternative way to sort a Map by keys, and put it into the "result" map
        Map<String, Integer> result2 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));


        // map 根据value 排序 根据value 进行降序排列
        LinkedHashMap<String, Integer> collect2 = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldV, newV) -> oldV, LinkedHashMap::new));

        //Alternative way
        Map<String, Integer> result3 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .forEachOrdered(x -> result3.put(x.getKey(), x.getValue()));


    }
}

你可能感兴趣的:(java开发日常总结,list集合转map,map排序)