Sort objects in ArrayList by date?

后端 未结 14 2128
生来不讨喜
生来不讨喜 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:08

    Given MyObject that has a DateTime member with a getDateTime() method, you can sort an ArrayList that contains MyObject elements by the DateTime objects like this:

    Collections.sort(myList, new Comparator<MyObject>() {
        public int compare(MyObject o1, MyObject o2) {
            return o1.getDateTime().lt(o2.getDateTime()) ? -1 : 1;
        }
    });
    
    0 讨论(0)
  • 2020-11-22 07:10

    With introduction of Java 1.8, streams are very useful in solving this kind of problems:

    Comparator <DateTime> myComparator = (arg1, arg2) 
                    -> {
                        if(arg1.lt(arg2)) 
                           return -1;
                        else if (arg1.lteq(arg2))
                           return 0;
                        else
                           return 1;
                       };
    
    ArrayList<DateTime> sortedList = myList
                       .stream()
                       .sorted(myComparator)
                       .collect(Collectors.toCollection(ArrayList::new));
    
    0 讨论(0)
  • 2020-11-22 07:15

    You can make your object comparable:

    public static class MyObject implements Comparable<MyObject> {
    
      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<MyObject>() {
      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<MyObject> {
    
      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<MyObject>() {
      public int compare(MyObject o1, MyObject o2) {
          if (o1.getDateTime() == null || o2.getDateTime() == null)
            return 0;
          return o1.getDateTime().compareTo(o2.getDateTime());
      }
    });
    
    0 讨论(0)
  • 2020-11-22 07:17

    You can use Collections.sort method. It's a static method. You pass it the list and a comparator. It uses a modified mergesort algorithm over the list. That's why you must pass it a comparator to do the pair comparisons.

    Collections.sort(myList, new Comparator<MyObject> {
       public int compare(MyObject o1, MyObject o2) {
          DateTime a = o1.getDateTime();
          DateTime b = o2.getDateTime();
          if (a.lt(b)) 
            return -1;
          else if (a.lteq(b)) // it's equals
             return 0;
          else
             return 1;
       }
    });
    

    Note that if myList is of a comparable type (one that implements Comparable interface) (like Date, Integer or String) you can omit the comparator and the natural ordering will be used.

    0 讨论(0)
  • 2020-11-22 07:18

    Future viewers, I think this is the simplest solution, if your model contains a string type date ("2020-01-01 10:00:00" for example), then just write the following line to sort the data by date descending from newest to the oldest:

    Collections.sort(messages, (o1, o2) -> o2.getMessageDate().compareTo(o1.getMessageDate()));
    
    0 讨论(0)
  • All the answers here I found to be un-neccesarily complex for a simple problem (at least to an experienced java developer, which I am not). I had a similar problem and chanced upon this (and other) solutions, and though they provided a pointer, for a beginner I found as stated above. My solution, depends on where in the the Object your Date is, in this case, the date is the first element of the Object[] where dataVector is the ArrayList containing your Objects.

    Collections.sort(dataVector, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return ((Date)o1[0]).compareTo(((Date)o2[0]));
        }
    });
    
    0 讨论(0)
提交回复
热议问题