list.sort java
Learn to use Collections.sort() method to sort a list of objects using some examples. Show
1. Sorting in Natural Order and Reverse OrderCollections.sort(list); //Sorts in natural order Collections.sort(list, Collections.reverseOrder()); //Sorts in reverse order
1.1. Sorting an ArrayList of StringsJava program to sort a list of strings lexicographically (in the dictionary order). List1.2. Sorting ArrayList of Objects by FieldWe may require to sort a list of custom objects which can have their own sorting logic. In this case, implement the Comparator interface in the custom class. For example, the domain object Employee has default sorting on the name field. Checkout for comparison logic in compareTo() method. public class Employee implements ComparableNest Java program sorts the list of Employee objects by their name; ArrayList2. Custom Sorting using ComparatorsThe second parameter in sort() method takes an instance of Comparator. We can implement any kind of comparison logic with the help of comparators and then we can use sort() method to sort the list based on the given custom logic. We can create a separate Comparator instances for each kind of sorting need, and then we can combine those instances to create group sorting effect. For example, if we want to sort the Employee list on three fields id, name, and age. In this case, we need to create 3 Comparator instances. 2.1. Creating Custom ComparatorThis is general syntax to create a Comparator in Java. In this case, we are creating a Comparator which will sort the Employee list by id field. ComparatorWe can use lambda expression for further shortening the syntax. 2.2. Using Comparator for SortingArrayList3. ConclusionIn the above code examples, we learned to sort an ArrayList in default order or reverse order. We also learned to use the Comparators for implementing the custom sorting logic. Happy Learning !! Was this post helpful?Let us know if you liked the post. Thats the only way we can improve. Yes No Further Reading:
|