zoukankan      html  css  js  c++  java
  • Map按键排序(sort by key)

    1.需求:已知有如下map,要求按照key倒序排列遍历。

    Map<String, Integer> map = new HashMap<>();
    map.put("1", 1);
    map.put("3", 3);
    map.put("2", 2);
    map.put("5", 5);
    map.put("4", 4);

     2.实现

    ①自定义排序方法,返回有序map

    private Map<String,Integer> sortMapByKey(Map<String, Integer> map) {
        if(CollectionUtils.isEmpty(map)){
            return null;
        }
        //treeMap适用于按自然顺序或自定义顺序遍历键(key)
        Map<String,Integer> treeMap = new TreeMap<>(new MapKeyComparator());
        treeMap.putAll(map);
        return treeMap;
    }

    ②自定义比较器,实现Comparator接口

    /**
     * 自定义比较器
     */
    class MapKeyComparator implements Comparator<String>{
    
        @Override
        public int compare(String str1, String str2) {
            return str2.compareTo(str1);
        }
    }

    ③遍历有序map

    @Test
    public void test1() {
        Map<String, Integer> map = new HashMap<>();
        map.put("1", 1);
        map.put("3", 3);
        map.put("2", 2);
        map.put("5", 5);
        map.put("4", 4);
        Map<String,Integer> resultMap = sortMapByKey(map);
        for (Map.Entry<String,Integer> entry:resultMap.entrySet()){
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
    }

    3.Java8实现按照key倒序排列遍历

    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("1", 1);
        map.put("3", 3);
        map.put("2", 2);
        map.put("5", 5);
        map.put("4", 4);
        Map<String, Integer> resultMap = new TreeMap<>((str1, str2) -> str2.compareTo(str1));
        resultMap.putAll(map);
        resultMap.forEach((key,value)-> System.out.println(key+":"+value));
    }
  • 相关阅读:
    HDU 2098 分拆素数和 数论
    CodeForces The Endless River
    CodeForces Good Words
    CodeForces A or B Equals C
    HDU 1251 统计难题 字典树/STL
    CSUOJ 1555 Inversion Sequence 线段树/STL
    OpenJudge P4979 海贼王之伟大航路 DFS
    敌兵布阵 线段树
    HDU 4004 The Frog's Games 二分
    HDU 2578 Dating with girls(1) 二分
  • 原文地址:https://www.cnblogs.com/ixan/p/9532490.html
Copyright © 2011-2022 走看看