对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;
    }

猜你喜欢

转载自blog.csdn.net/qq_45752401/article/details/125104940