sort year,month of date

该篇文章展示了如何使用Java通过自定义比较器对日期按年月进行排序,并将它们分组到相应的年月键下。作者提供了一个示例,展示如何处理LocalDate对象列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

To sort a list of dates by year and month in ascending order and then group them, you can follow these steps:

  1. Define a custom comparator to sort the dates by year and month.
  2. Sort the list using the custom comparator.
  3. Group the sorted dates by year and month.

Here's a Java example demonstrating this approach:

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // Sample list of dates
        List<LocalDate> dates = new ArrayList<>();
        dates.add(LocalDate.of(2022, 4, 15));
        dates.add(LocalDate.of(2021, 11, 25));
        dates.add(LocalDate.of(2023, 2, 10));
        dates.add(LocalDate.of(2022, 6, 5));
        dates.add(LocalDate.of(2021, 10, 10));
        dates.add(LocalDate.of(2022, 4, 1));
        
        // Sort the dates by year and month
        Comparator<LocalDate> comparator = Comparator.comparing(LocalDate::getYear)
                .thenComparing(LocalDate::getMonth);
        List<LocalDate> sortedDates = dates.stream()
                .sorted(comparator)
                .collect(Collectors.toList());
        
        // Group the sorted dates by year and month
        Map<String, List<LocalDate>> groupedDates = new HashMap<>();
        for (LocalDate date : sortedDates) {
            String yearMonth = date.getYear() + "-" + date.getMonthValue();
            groupedDates.computeIfAbsent(yearMonth, k -> new ArrayList<>()).add(date);
        }
        
        // Print the grouped dates
        groupedDates.forEach((key, value) -> {
            System.out.println(key + ": " + value);
        });
    }
}

This code will output the sorted dates grouped by year and month:

2021-10: [2021-10-10]
2021-11: [2021-11-25]
2022-4: [2022-04-01, 2022-04-15]
2022-6: [2022-06-05]
2023-2: [2023-02-10]

This approach first sorts the dates using a custom comparator based on the year and month. Then, it groups the sorted dates by concatenating the year and month into a string key for each group. Finally, it prints the grouped dates.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值