如何使用空值对集合进行排序并在之后反转列表?

Jer*_*emy 4 java sorting null

所以我正在处理一个日期列表,其中一些值为“”,即空值。我使用了How to handle nulls when using Java collection sort的答案

public int compare(MyBean o1, MyBean o2) {
    if (o1.getDate() == null) {
        return (o2.getDate() == null) ? 0 : -1;
    }
    if (o2.getDate() == null) {
        return 1;
    }
    return o2.getDate().compareTo(o1.getDate());
} 
Run Code Online (Sandbox Code Playgroud)

以两个升序对列表进行排序,将空值放在首位。

我想要的是按升序先有空值,然后像上面的代码那样按升序排列值。然后选择下降时以字面上翻转列表。IE 列表中的第一个值按降序排列,然后是所有空值。

在按升序对列表进行排序后,我尝试了以下操作Collections.reverseOrder(); 首先保留空值,然后按降序对日期进行排序。

我也试过了Collections.reverse(List)。这将空值放在列表的末尾,但按升序保持日期。

Lou*_*man 6

在 Java 8 中,这一切都可以是

Collections.sort(list, 
     Comparator.comparing(MyBean::getDate, 
        Comparator.nullsFirst(Comparator.naturalOrder()))
     .reversed());
Run Code Online (Sandbox Code Playgroud)


hem*_*900 2

您可以通过一个简单的比较器来实现这一点。根据您的自定义 bean 对象修改它。像这样的东西 -

public class DateComparator implements Comparator<Date> {

    private boolean reverse;

    public DateComparator(boolean reverse) {
        this.reverse = reverse;
    }

    public int compare(Date o1, Date o2) {
        if (o1 == null || o2 == null) {
            return o2 != null ? (reverse ? 1 : -1) : (o1 != null ? (reverse ? -1 : 1) : 0);
        }
        int result = o1.compareTo(o2);
        return reverse ? result * -1 : result;
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        Date[] dates = new Date[]{null, dateFormat.parse("10-10-2013"), null, dateFormat.parse("10-10-2012"), dateFormat.parse("10-10-2015"), dateFormat.parse("10-10-2011"), null};
        List<Date> list = Arrays.asList(dates);
        Collections.sort(list, new DateComparator(false));
        System.out.println(list);
        Collections.sort(list, new DateComparator(true));
        System.out.println(list);
    }
}
Run Code Online (Sandbox Code Playgroud)