Stream Map 的排序

根据key排序

public static void main(String[] argv) {

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

        System.out.println("Original...");
        System.out.println(map);

        //重声一个map用来装排序后的值
        Map<String, Integer> result = new LinkedHashMap<>();

        //sort by key, a,b,c..., and put it into the "result" map
        map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));

        System.out.println("Sorted...");
        System.out.println(result);

    }

根据value排序

   public static void main(String[] argv) {

        Map<String, Integer> map = new HashMap<>();
        map.put("z", 10);
        map.put("b", 5);
        map.put("a", 6);
        map.put("c", 20);
        map.put("d", 1);
        map.put("e", 7);
        map.put("y", 8);
        map.put("n", 99);
        map.put("j", 50);
        map.put("m", 2);
        map.put("f", 9);
        System.out.println("Original...");
        System.out.println(map);
        //重声一个map用来装排序后的值
        Map<String, Integer> result = new LinkedHashMap<>();
        //sort by key, a,b,c..., and put it into the "result" map
        map.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())  // reversed倒序,不指定类型,会默认为<java.util.Map.Entry<java.lang.Object,V>>
                .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));

        System.out.println("Sorted...");
        System.out.println(result);

    }

 

posted @ 2020-05-13 10:02  迸发图强  阅读(3915)  评论(0编辑  收藏  举报