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.
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.
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!
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