Sort objects in ArrayList by date?

后端 未结 14 2341
生来不讨喜
生来不讨喜 2020-11-22 06:58

Every example I find is about doing this alphabetically, while I need my elements sorted by date.

My ArrayList contains objects on which one of the datamembers is a

14条回答
  •  日久生厌
    2020-11-22 07:15

    You can make your object comparable:

    public static class MyObject implements Comparable {
    
      private Date dateTime;
    
      public Date getDateTime() {
        return dateTime;
      }
    
      public void setDateTime(Date datetime) {
        this.dateTime = datetime;
      }
    
      @Override
      public int compareTo(MyObject o) {
        return getDateTime().compareTo(o.getDateTime());
      }
    }
    

    And then you sort it by calling:

    Collections.sort(myList);
    

    However sometimes you don't want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:

    Collections.sort(myList, new Comparator() {
      public int compare(MyObject o1, MyObject o2) {
          return o1.getDateTime().compareTo(o2.getDateTime());
      }
    });
    

    However, the above works only if you're certain that dateTime is not null at the time of comparison. It's wise to handle null as well to avoid NullPointerExceptions:

    public static class MyObject implements Comparable {
    
      private Date dateTime;
    
      public Date getDateTime() {
        return dateTime;
      }
    
      public void setDateTime(Date datetime) {
        this.dateTime = datetime;
      }
    
      @Override
      public int compareTo(MyObject o) {
        if (getDateTime() == null || o.getDateTime() == null)
          return 0;
        return getDateTime().compareTo(o.getDateTime());
      }
    }
    

    Or in the second example:

    Collections.sort(myList, new Comparator() {
      public int compare(MyObject o1, MyObject o2) {
          if (o1.getDateTime() == null || o2.getDateTime() == null)
            return 0;
          return o1.getDateTime().compareTo(o2.getDateTime());
      }
    });
    

提交回复
热议问题