Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort an ArrayList in ascending order using Collections and Comparator

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!

like image 607
user1097097 Avatar asked Dec 15 '11 17:12

user1097097


People also ask

How do you arrange an ArrayList in ascending order?

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.

How do you sort an array in ascending order using Comparator in Java?

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.

How do you sort elements in an ArrayList using Comparator interface?

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.

Can you use Collections sort on ArrayList?

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.


2 Answers

Just throwing this out there...Can't you just do:

Collections.sort(myarrayList);

It's been awhile though...

like image 104
Cody S Avatar answered Nov 05 '22 07:11

Cody S


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); 
like image 41
Sean Patrick Floyd Avatar answered Nov 05 '22 06:11

Sean Patrick Floyd