java中list数据按照月份分组
时间: 2024-09-29 17:10:44 浏览: 70
在Java中,如果你有一个List集合,其中包含一些日期对象,比如Month类型的日期,想要按照月份分组,你可以使用Collections.sort()函数配合自定义的Comparator,或者使用Stream API以及Collectors.groupingBy()方法。这里是一个基本的例子:
```java
import java.util.*;
import java.time.Month;
public class MonthlyGroupingExample {
List<Date> dates; // 假设这是你的日期列表
public void groupByMonth() {
// 使用排序并根据月份创建一个新的Map
Collections.sort(dates, Comparator.comparing(d -> d.getMonth()));
Map<Month, List<Date>> groupedDates = new TreeMap<>((a, b) -> a.getValue().compareTo(b.getValue()));
for (Date date : dates) {
Month month = date.getMonth();
if (!groupedDates.containsKey(month)) {
groupedDates.put(month, new ArrayList<>());
}
groupedDates.get(month).add(date);
}
// 或者使用Java 8 Stream API
Map<Month, List<Date>> streamGrouped = dates.stream()
.collect(Collectors.groupingBy(Date::getMonth));
System.out.println(groupedDates); // 打印每个月份及其对应的日期列表
}
}
```
在这个例子中,我们首先对日期列表按月份排序,然后使用TreeMap保持月份数字顺序。如果需要,也可以使用HashMap作为key-value对,但不会有默认的排序。
阅读全文
相关推荐


















