对HashMap的key进行排序

 public static LinkedHashMap<String, List<AirQualityRankingResp>> mapSortedByKey(Map<String, List<AirQualityRankingResp>> param) {
        // 分组后根据key正序排列,()LinkedHashMap有序)
        LinkedHashMap<String, List<AirQualityRankingResp>> collect = param.entrySet().stream().sorted(new Comparator<Map.Entry<String, List<AirQualityRankingResp>>>() {
            @Override
            public int compare(Map.Entry<String, List<AirQualityRankingResp>> o1, Map.Entry<String, List<AirQualityRankingResp>> o2) {
                try {
                    Date d1 = new SimpleDateFormat("yyyy-MM").parse(o1.getKey());
                    Date d2 = new SimpleDateFormat("yyyy-MM").parse(o2.getKey());
                    return d1.compareTo(d2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        }).collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldVal, newVal) -> oldVal,
                LinkedHashMap::new
        ));
        return collect;
    }

你可能感兴趣的:(后端,#,java,java,排序算法,开发语言)