0
点赞
收藏
分享

微信扫一扫

使用Stream对HashMap进行排序

杰克逊爱学习 2021-09-28 阅读 87

话不多说。直接贴代码

        HashMap<String, BigDecimal> map = new HashMap<>();
        map.put("a", BigDecimal.valueOf(1231));
        map.put("d", BigDecimal.valueOf(55));
        map.put("c", BigDecimal.valueOf(223));
        LinkedHashMap<String, BigDecimal> collect = map.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        collect.entrySet().stream().forEach(c-> System.out.println(c.getKey()+" "+c.getValue()));

Result

按照特定序列进行排序

        List<String> rules = Arrays.asList("a", "d", "c");
        HashMap<String, BigDecimal> map = new HashMap<>();
        map.put("a", BigDecimal.valueOf(1));
        map.put("d", BigDecimal.valueOf(2));
        map.put("c", BigDecimal.valueOf(3));
        LinkedHashMap<String, BigDecimal> collect = map.entrySet().stream().sorted(Comparator.comparingInt(k -> rules.indexOf(k.getKey())))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        collect.entrySet().stream().forEach(c-> System.out.println(c.getKey()+" "+c.getValue()));

Result

Collects.toMap的妙用

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("a","a");
        hashMap.put("b","b");
        hashMap.put("c","c");
        hashMap.put("d","d");
        hashMap.put("e","e");
        hashMap.put("f","f");
        List<String> re = Arrays.asList("a", "b", "c");
        Map<String, Object> resultMap = re.stream().collect(Collectors.toMap(key -> key, hashMap::get));
        resultMap.forEach((k,v)-> System.out.println(k+","+v));

输出:


举报

相关推荐

0 条评论