Java Joda-Time,将LocalDate分配给Month和Year

0 java jodatime

我之前从未使用过Joda-Time,但我有ArrayList,其中包含具有LocalDate和count的对象.所以我在ArrayList中计算每一天,每天只在ArrayList中使用一次.我需要计算一年中每个月的计数,这在列表中.

我的数据:例如:

dd.MM.yyyy
17.01.1996 (count 2)
18.01.1996 (count 3)
19.02.1996 (count 4)
19.03.1996 (count 1)
18.05.1997 (count 3)
Run Code Online (Sandbox Code Playgroud)

现在我想要outpur像这样:

MM.yyyy
01.1996 -> 2 (17.1.1996) +  3 (18.1.1996) = 5
02.1996 -> 4 (19.2.1996)                  = 4
03.1996 -> 1 (19.3.1996)                  = 1
05.1997 -> 3 (18.5.1997)                  = 3
Run Code Online (Sandbox Code Playgroud)

我只需要每个月计算,但我不知道最好的方法是什么.

数据类:

private class Info{
   int count;
   LocalDate day;
}
Run Code Online (Sandbox Code Playgroud)

结果我会在一些包含月份和年份日期+计数的类中输入.

Adr*_*hum 5

Joda-Time中,有一个表示Year + Month信息的类,名为YearMonth.

您需要做的主要是构建一个Map<YearMonth, int>存储每个的计数YearMonth,通过循环List包含LocalDate和计数的原始,并相应地更新地图.

转换LocalDateYearMonth应该是直截了当的:YearMonth yearMonth = new YearMonth(someLocalDate);应该工作

在伪代码中,它看起来像:

List<Info> dateCounts = ...;
Map<YearMonth, Integer> monthCounts = new TreeMap<>();

for (Info info : dateCounts) {
    YearMonth yearMonth = new YearMonth(info.getLocalDate());
    if (monthCounts does not contains yearMonth) {
        monthCounts.put(yearMonth, info.count);
    } else {
        oldCount = monthCounts.get(yearMonth);
        monthCounts.put(yearMonth, info.count + oldCount);
    }
}

// feel free to output content of monthCounts now.
// And, with TreeMap, the content of monthCounts are sorted
Run Code Online (Sandbox Code Playgroud)