简体   繁体   中英

Sorting of Date ArrayList

I have an ArrayList which contains dates with a format (Satuday,4 Februray 2012). How can I sort this ArrayList ?

这是最简单的排序方法之一,

Collections.sort(<Your Array List>);

If you have any special requirements while sorting, so you may do it by providing your own Comparator . For example:

//your List
ArrayList<Date> d = new ArrayList<Date>();

//Sorting
Collections.sort(d, new Comparator<Date>() {
    @Override
    public int compare(Date lhs, Date rhs) {
        if (lhs.getTime() < rhs.getTime())
            return -1;
        else if (lhs.getTime() == rhs.getTime())
            return 0;
        else
            return 1;
    }
});

The key element is that you are converting your Date object into milliseconds (using getTime() ) for comparison.

After 8 years..

List<Date> dates = datelist;
List<Date> sorted = dates.stream()
  .sorted(Comparator.comparingLong(Date::getTime))
  .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM