In this tutorials, you will create 6 Person objects and add all into an ArrayList, and use the sort tag to sort the ArrayList based on the Person’s property. Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). To use this Struts 2 sort tag, you have to understand how java.util.Comparator work, please read this article – Java object sorting with Comparator. Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms.This solution requires rewriting the whole sorting code for different criterion like Roll No. and Name. La classe Collections possède une autre méthode Collections.sort(List, Comparator) qui permet de trier un ArrayList dans l'ordre croissant et décroissant. […] UnsupportedOperationException − Throws if the specified list's list-iterator does not support the set operation.
If you try to sort a list, the elements of which do not implement Comparable, Collections.sort(list) will throw a ClassCastException.Similarly, Collections.sort(list, comparator) will throw a ClassCastException if you try to sort a list whose elements cannot be compared to one another using the comparator.Elements that can be compared to one another are called mutually comparable. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Basically, in Java 7, we were using Collections.sort() that was accepting a List and, eventually, a Comparator – in Java 8 we have the new List.sort(), which accepts a Comparator. Cette fonction utilise un comparateur d'objets qui à chaque fois compare deux objets avec la fonction o1.compareTo(o2) . Struts 2 sort tag is used to sort a List using a java.util.Comparator. ClassCastException − Throws if the list contains elements that are not mutually comparable using the specified comparator. Comparator example – Collections sort with/without Lambda in Java 8 Post Views: 2,468 One way is through traditional way by using Comparator class and in next example, we will see how to use Lambda expression that came into existence since Java 8 to sort the collections and making the code much elegant and declarative.