时间范围内的按时间统计的每日数据填充

老有同事问我写写统计图标的问题,例如按照日期范围每日的数据信息展示,我就写个例子放在这里,再问打死。

public class ResultVo {

    public static void main(String[] args) {

        LocalDate startDate = LocalDate.of (2021,2,1);
        LocalDate endDate = LocalDate.of (2021,3,1);

        List<TestData> formDbList= new ArrayList<TestData>(){{
            add(TestData.builder().dateStr("20210202").otherData("A").build());
            add(TestData.builder().dateStr("20210214").otherData("B").build());
            add(TestData.builder().dateStr("20210301").otherData("C").build());
        }};
        long apart = ChronoUnit.DAYS.between(startDate, endDate);
        List<TestData> newData = new ArrayList<>();
        if (dex > 0) {
            Stream.iterate(startDate, d -> d.plusDays(1)).limit(apart + 1).forEach(f -> {
                String dateKey= f.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                Optional<TestData> dbData = formDbList.stream().filter(fdl -> dateKey.equals(fdl.dateStr)).findFirst();
                if (dbData.isPresent()) {
                    newData.add(dbData.get());
                    return;
                }
                newData.add(TestData.builder().dateStr(dateKey).otherData("没有数据").build());

            });
        }
        newData.sort((a,b)-> {
            if (Integer.parseInt(a.dateStr)>Integer.parseInt(b.dateStr)) {
                return 1;
            }else{
                return  -1;
            }
        });

        System.out.println(newData);

    }

    @Data
    @Builder
    public  static  class  TestData {
        private  String dateStr;
        private  String otherData;
    }
}

相应的,同样的方式还可以写其他时间格式。

原文地址:https://www.cnblogs.com/akashicbrother/p/14964135.html