@Data
@AllArgsConstructor(staticName = "of")
static class Student {
private String name;
private int age;
private String birthday;
}
public static void main(String[] args) {
Student student = Student.of("吕小军", 21, "2000-06-01");
Student student1 = Student.of("赵小明", 18, "2001-06-01");
Student student2 = Student.of("钱小红", 24, "2000-06-01");
Student student3 = Student.of("孙大手", 23, "2000-06-01");
Student student4 = Student.of("李大脚", 31, "2002-06-01");
Student student5 = Student.of("王权", 41, "2001-06-01");
Student student6 = Student.of("李动宾", 21, "2001-06-01");
Student student7 = Student.of("吕尚", 61, "2002-06-01");
Student student8 = Student.of("和珅", 32, "2000-02-01");
Student student9 = Student.of("尚气", 22, "2000-01-01");
Student student10 = Student.of("瓜娃", 25, "2000-12-01");
List<Student> list = Arrays.asList(student, student1, student2, student3, student4, student5, student6,
student7, student8, student9, student10);
// 创建指定年份范围内所有月份的集合
Set<String> allMonths = new TreeSet<>();
for (int year = 2000; year <= 2002; year++) {
for (int month = 1; month <= 12; month++) {
allMonths.add(year + "-" + String.format("%02d", month));
}
}
// 统计每个月份出生的学生
Map<String, List<Student>> initialGrouping = list.stream()
.filter(s -> s.getBirthday() != null)
.collect(Collectors.groupingBy(s -> s.getBirthday().substring(0, 7)));
// 确保每个月份都有记录,没有则置为空集合
Map<String, List<Student>> monthlyBirths = allMonths.stream()
.collect(Collectors.toMap(
month -> month,
month -> initialGrouping.getOrDefault(month, Collections.emptyList())
));
// 打印结果
monthlyBirths.forEach((month, students) ->
System.out.println("Month: " + month + ", Students: " + students));
}
统计近三年每个月数据:每个月份出生的学生清单
最新推荐文章于 2024-09-13 21:40:38 发布