Saurabh
Saurabh

Reputation: 995

Sorting of Date ArrayList

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

Upvotes: 8

Views: 38327

Answers (4)

Nan0fire
Nan0fire

Reputation: 189

After 12 years...

final var sortedDates = dates.stream().sorted().toList();

Upvotes: 0

Occlumency
Occlumency

Reputation: 148

After 8 years..

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

Upvotes: 5

waqaslam
waqaslam

Reputation: 68177

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.

Upvotes: 5

Aerrow
Aerrow

Reputation: 12134

This is one of the Simplest way to sort,

Collections.sort(<Your Array List>);

Upvotes: 23

Related Questions