How to sort an ArrayList
in ascending order using Comparator
? I know how to sort it in descending order using:
Comparator mycomparator = Collections.reverseOrder();
then
Collections.sort(myarrayList,mycomparator);
just want to know how to sort it in ascending order using Collections and comparator? Thanks!
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 as the parameter and returns a Collection sorted in the Ascending Order by default.
In java, a Comparator is provided in java. To sort an ArrayList using Comparator override the compare() method provided by the comparator interface. Override the compare() method in such a way that it will reorder an ArrayList in descending order instead of ascending order.
We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.
Collections. sort() works for objects Collections like ArrayList, LinkedList, etc. We can use Collections. sort() to sort an array after creating an ArrayList of given array items.
Just throwing this out there...Can't you just do:
Collections.sort(myarrayList);
It's been awhile though...
Use the default version:
Collections.sort(myarrayList);
Of course this requires that your Elements implement Comparable
, but the same holds true for the version you mentioned.
BTW: you should use generics in your code, that way you get compile-time errors if your class doesn't implement Comparable. And compile-time errors are much better than the runtime errors you'll get otherwise.
List<MyClass> list = new ArrayList<MyClass>();
// now fill up the list
// compile error here unless MyClass implements Comparable
Collections.sort(list);
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