相对于当前日期对Java集合进行排序

问题描述:

我想对相对于当前日期的日期列表进行排序,例如,列表中有下一项:

I want to sort my List of Date relative to the current date, e.g we have next items in list:

10.01.2018, 
10.20.2018, 
10.14.2018, 
10.02.2018 

,当前日期为10.08.2018.

结果应按以下顺序升序排列数组:

The result should be ascending sort of array in the next order:

10.14.2018, 
10.20.2018    and then 
10.01.2018, 
10.02.2018. 

首先应该是没有发生的日期,然后是过去的日期.如何使用Comparator?

First should be dates that didn't happen and then the past dates. How to do it with Comparator?

您可以看到这种方式

  • 如果您要比较的两个日期在今天的同一侧(之前或之后),请正常进行比较
  • 如果您之前需要一个,之后需要一个来取消订单

这将保留ascending order,但将将来的日期放在过去的日期之前

This will keep ascending order but put future dates before past dates

public static void main(String[] args) {
    List<LocalDate> list = Arrays.asList(
                                      LocalDate.of(2018, 10, 1), LocalDate.of(2018, 10, 20),
                                      LocalDate.of(2018, 10, 14),LocalDate.of(2018, 10, 2));
    System.out.println(list);
    LocalDate now = LocalDate.now();

    list.sort((o1, o2) -> {
        if (o1.isBefore(now) && o2.isBefore(now) || o1.isAfter(now) && o2.isAfter(now)) {
            return o1.compareTo(o2);
        }
        return o2.compareTo(o1);
    });

    System.out.println(list);
}


[2018-10-01, 2018-10-20, 2018-10-14, 2018-10-02]
[2018-10-14, 2018-10-20, 2018-10-01, 2018-10-02]