【问题标题】:How to sort collection with null's and invert the list afterwards?如何使用 null 对集合进行排序并在之后反转列表?
【发布时间】:2015-03-17 16:06:38
【问题描述】:

所以我正在处理一个日期列表,其中一些值是“”,即空值。我使用了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());
} 

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

我想要的是按升序先有空值,然后再按升序排列值,就像上面的代码一样。 Then when descending is selected to literally flip the list. IE 列表中的第一个值按降序排列,然后是所有空值。

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

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

【问题讨论】:

    标签: java sorting null


    【解决方案1】:

    在 Java 8 中,这一切都可以

    Collections.sort(list, 
         Comparator.comparing(MyBean::getDate, 
            Comparator.nullsFirst(Comparator.naturalOrder()))
         .reversed());
    

    【讨论】:

      【解决方案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);
          }
      }
      

      【讨论】:

        【解决方案3】:

        这应该有效:

        if (o1.getDate() == null) {
            return (o2.getDate() == null) ? 0 : -1;
        }
        if (o2.getDate() == null) {
            return -1;
        }
        return o2.getDate().compareTo(o1.getDate());
        

        我不完全确定您是否希望非空日期按升序或降序排列,但在 o2.getDate().compareTo(o1.getDate()) 之前放置一个 - 应该可以解决问题。

        【讨论】:

          猜你喜欢
          • 2017-08-14
          • 1970-01-01
          • 1970-01-01
          • 2011-02-10
          • 1970-01-01
          • 2015-05-27
          • 2016-07-14
          • 1970-01-01
          • 2011-04-04
          相关资源
          最近更新 更多