Friday, August 16, 2013

How to Sort List in reverse Order in Java Collection Framework with Example

Java Collection Framework provides a convenient reverse comparator, to sort List of objects in reverse order. You can obtain reverse Comparator, by calling Collections.reverseOrder(), which by default sort List of Integer in reverse numeric order and List of String in reverse alphabetic order. It actually reverse natural ordering of objects imposed by Comparable interface. Apart from this method, Collections class also provides an overloaded method Collections.reverseOrder(Comparatorcmp), which takes a Comparator, and sort List on reverse order of that Comparator. So next time if you need to sort your Collection in reverse order, you don�t need to write any extra comparator by yourself, you can directly leverage reverse comparator provided by java.util.Collections class. It is as simple as calling Collections.sort() method providing comparator wrapped into Collections.reverseOrder() method. By using these two methods, you can sort any Listimplementation e.g. ArrayList, LinkedListor Vectorin Java.
Read more �

No comments:

Post a Comment