map按key或者value排序

 public static void main(String[] args) {
        // TreeMap 按key 升序
        Map map1 = new TreeMap<>();
        map1.put(3, "asdasd");
        map1.put(1, "qweasd");
        map1.put(2, "asd");
        map1.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });
        System.out.println("-------------------------------------------");
        // TreeMap 按key 降序
        Map map2 = new TreeMap<>((o1, o2) -> o2 - o1);
        map2.put(3, "asdasd");
        map2.put(1, "qweasd");
        map2.put(2, "asd");
        map2.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });
        System.out.println("-------------------------------------------");
        // Map  按value 升序  转换为list排序
        Map map3 = new HashMap<>();
        map3.put(5, 2);
        map3.put(6, 32);
        map3.put(3, 2);
        map3.put(4, 11);
        List> list = new ArrayList<>(map3.entrySet());
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        // 注意此处不能这样for循环,map存的还是map一开始的数据
//        map3.forEach((key, value) -> {
//            System.out.println(key + ":" + value);
//        });
        for (Map.Entry entry:list){
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        // map倒序访问   ListIterator可以往前访问,iterator不行
        ListIterator> li = new ArrayList<>(map3.entrySet()).iterator(map3.size());
        while (li.hasPrevious()) {
            Map.Entry entry = li.previous();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        System.out.println("-------------------------------------------");
        // 正序
        while (li.hasNext()) {
            Map.Entry entry = li.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }

你可能感兴趣的:(JAVA基础,java,elementui,蓝桥杯)