Sort objects in ArrayList by date?

2018-12-31 11:34发布

Can someone help me with this? 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 DateTime object. On DateTime I can call the functions:

lt() // less-than
lteq() // less-than-or-equal-to

So to compare I could do something like:

if(myList.get(i).lt(myList.get(j))){
    // ...
}

I don't really know what to do inside the if block. Any ideas?

11条回答
永恒的永恒
3楼-- · 2018-12-31 12:25
list.sort(Comparator.comparing(o -> o.getDateTime()));

The best answer IMHO from Tunaki using Java 8 lambda

查看更多
临风纵饮
4楼-- · 2018-12-31 12:26

Since Java 8 the List interface provides the sort method. Combined with lambda expression the easiest solution would be

// sort DateTime typed list
list.sort((d1,d2) -> d1.compareTo(d2));
// or an object which has an DateTime attribute
list.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));
// or like mentioned by Tunaki
list.sort(Comparator.comparing(o -> o.getDateTime()))
查看更多
唯独是你
5楼-- · 2018-12-31 12:30

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));
查看更多
与风俱净
6楼-- · 2018-12-31 12:35

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]));
    }
});
查看更多
登录 后发表回答