8

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

5
  • 1
    What have u done ? to do so ? have u tried ? Commented Sep 24, 2012 at 8:36
  • what class are you using for your dates? Commented Sep 24, 2012 at 8:39
  • In which kind you need to start either day or date or year? Commented Sep 24, 2012 at 8:40
  • Dates with a format? Do you mean the dates are stored as strings? Because java.util.Date objects do not have a format by themselves. Commented Sep 24, 2012 at 9:26
  • I tried using Collections.sort()....I have four to five date items in array list in the format "Saturday,4 Februray 2012"...I have to sort them to display in a order by latest to older one. Commented Sep 24, 2012 at 11:35

4 Answers 4

23

This is one of the Simplest way to sort,

Collections.sort(<Your Array List>);
Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

Else just use Collections.sort(<Your Array List>); as @Aerrow said. Dates are comparable.
5

After 8 years..

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

Comments

0

After 12 years...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.