時間範圍內的按時間統計的每日資料填充
阿新 • • 發佈:2021-07-02
老有同事問我寫寫統計圖示的問題,例如按照日期範圍每日的資料資訊展示,我就寫個例子放在這裡,再問打死。
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; } }