Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic comparator to sort Java Collections (List, Set)

I need some generic comparator which would accept instances of List or Set as an argument, and order direction argument (ASC, DESC), and then return the sorted collection. I can not seem to find on internet this example, and am in a horrible rush. I know I dont ask question in appropriate way, since I dont have any code to begin with but am in a horrible rush. Collections will contain objects which implement comparable and dates.

Any examples, implementations very much appreciated. Thank you.

like image 726
Julia Avatar asked Jun 27 '26 06:06

Julia


2 Answers

The Collections class has a reverseOrder method which returns a comparator for a generic type T which should satisfy your requirement for the DESC comparator. If you are passing your Collection to the Collections.sort() method, it automatically uses the ASC sort.

Also, "sorting" doesn't mean a lot when it comes to "sets" which maintain "unique" elements in an unordered fashion (I mean you can use TreeSet for sorted sets, but that's a different story). A simple workaround would be to make a List out of the Set and pass it to Collections.sort.

like image 170
Sanjay T. Sharma Avatar answered Jun 28 '26 20:06

Sanjay T. Sharma


Using GenericComparator.java you will be able to sort following datatypes Integer, String, Long, Double, Float, and Date.

For Ascending order

Collections.sort(persons, new GenericComparator("name", true));

For Descending order

Collections.sort(persons, new GenericComparator("name", false));

Detailed information here!

like image 21
jeevatkm Avatar answered Jun 28 '26 20:06

jeevatkm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!