How do I sort ArrayList of DateTime objects in descending order?
Thank you.
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted and Collections. reverseOrder() as the parameter and returns a Collection sorted in the Descending Order.
Inside the compare method for return value use the compareTo() method which will return the specified value by comparing the DateItem objects. Now in the main method use Collections. sort() method and pass the ArrayList and 'SortItem' class object to it, it will sort the dates, and output will be generated.
Sort Array in Descending OrderJava Collections class provides the reverseOrder() method to sort the array in reverse-lexicographic order. It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter.
First of all, unless you are stuck with using framework 1.1, you should not be using an ArrayList
at all. You should use a strongly typed generic List<DateTime>
instead.
For custom sorting there is an overload of the Sort
method that takes a comparer. By reversing the regular comparison you get a sort in descending order:
list.Sort(delegate(DateTime x, DateTime y){ return y.CompareTo(x); });
With lambda expressions in C# 3, the delegate is easier to create:
list.Sort((x, y) => y.CompareTo(x));
As "Guffa" already said, you shouldn't be using ArrayList
unless you are in .NET 1.1; here's a simpler List<DateTime>
example, though:
List<DateTime> dates = ... // init and fill
dates.Sort();
dates.Reverse();
Your dates are now sorted in descending order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With