java quarter如何進(jìn)行數(shù)據(jù)分組

小樊
83
2024-09-06 15:53:15

在Java中,你可以使用java.time包中的YearMonth類(lèi)來(lái)實(shí)現(xiàn)按季度分組的功能。以下是一個(gè)簡(jiǎn)單的示例:

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QuarterGrouping {
    public static void main(String[] args) {
        List<LocalDate> dates = new ArrayList<>();
        dates.add(LocalDate.of(2021, 1, 1));
        dates.add(LocalDate.of(2021, 3, 31));
        dates.add(LocalDate.of(2021, 4, 1));
        dates.add(LocalDate.of(2021, 6, 30));
        dates.add(LocalDate.of(2021, 7, 1));
        dates.add(LocalDate.of(2021, 9, 30));
        dates.add(LocalDate.of(2021, 10, 1));
        dates.add(LocalDate.of(2021, 12, 31));

        Map<Integer, List<LocalDate>> groupedDates = groupByQuarter(dates);
        for (Map.Entry<Integer, List<LocalDate>> entry : groupedDates.entrySet()) {
            System.out.println("Quarter " + entry.getKey() + ": " + entry.getValue());
        }
    }

    public static Map<Integer, List<LocalDate>> groupByQuarter(List<LocalDate> dates) {
        Map<Integer, List<LocalDate>> groupedDates = new HashMap<>();
        for (LocalDate date : dates) {
            YearMonth yearMonth = YearMonth.from(date);
            int quarter = getQuarter(yearMonth);
            if (!groupedDates.containsKey(quarter)) {
                groupedDates.put(quarter, new ArrayList<>());
            }
            groupedDates.get(quarter).add(date);
        }
        return groupedDates;
    }

    public static int getQuarter(YearMonth yearMonth) {
        int month = yearMonth.getMonthValue();
        if (month >= 1 && month <= 3) {
            return 1;
        } else if (month >= 4 && month <= 6) {
            return 2;
        } else if (month >= 7 && month <= 9) {
            return 3;
        } else {
            return 4;
        }
    }
}

這個(gè)示例首先創(chuàng)建了一個(gè)包含多個(gè)LocalDate對(duì)象的列表。然后,我們使用groupByQuarter方法將這些日期按季度分組。groupByQuarter方法遍歷日期列表,并使用YearMonth.from()方法將每個(gè)日期轉(zhuǎn)換為YearMonth對(duì)象。接下來(lái),我們使用getQuarter方法根據(jù)月份確定季度,并將日期添加到相應(yīng)的季度列表中。最后,我們打印出按季度分組的日期。

0