Java list sort descending
Learn to sort a Set, List and Map of primitive types and custom objects in Java 7 and Java 8. We will learn to sort in ascending and descending order as well. Show 1. Sorting an ArrayUse java.util.Arrays.sort() method to sort a given array in variety of ways. 1.1. Sort array in ascending orderJava program to sort an array of integers in ascending order using Arrays.sort() method. //Unsorted array Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 520, 1123, 366, 420 }; //Sort the array Arrays.sort(numbers); //Print array to confirm System.out.println(Arrays.toString(numbers));Program output. [9, 11, 15, 18, 47, 55, 366, 420, 520, 1123]1.2. Sort array in descending orderJava provides Collections.reverseOrder() comparator to reverse the default sorting behavior in one line. Use this to sort an array in descending order. //Unsorted array Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 520, 1123, 366, 420 }; //Sort the array in reverse order Arrays.sort(numbers, Collections.reverseOrder()); //Print array to confirm System.out.println(Arrays.toString(numbers));Program output. [1123, 520, 420, 366, 55, 47, 18, 15, 11, 9]1.3. Sorting a given array rangeArrays.sort() method is overloaded method and takes two additional parameters i.e. fromIndex (inclusive) and toIndex (exclusive). When provided, array will be sorted within provided range from position fromIndex to position toIndex. Given example sort the array from element 9 to 18. i.e. {9, 55, 47, 18} will be sorted and the rest elements will not be touched. //Unsorted array Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 }; //Sort the array Arrays.sort(numbers, 2, 6); //Print array to confirm System.out.println(Arrays.toString(numbers));Program output. [15, 11, 9, 18, 47, 55, 1123, 520, 366, 420]1.4. Java 8 parallel sortingJava 8 introduced lots of new APIs for parallel processing data sets and streams. One such API is Arrays.parallelSort(). The parallelSort() method breaks the array into multiple sub-arrays and each sub-array is sorted with Arrays.sort() in different threads. Finally, all sorted sub-arrays are merged into one sorted array. The output of the parallelSort() and sort(), both APIs, will be same at last. Its just a matter of leveraging the Java concurrency. //Parallel sort complete array Arrays.parallelSort(numbers); //Parallel sort array range Arrays.parallelSort(numbers, 2, 6); //Parallel sort array in reverse order Arrays.parallelSort(numbers, Collections.reverseOrder());2. Sorting a ListUse Collections.sort() API for sorting a List in Java 7. This API uses a modified mergesort and offers guaranteed n log(n) performance. 2.1. Sort List in ascending order//Unsorted list Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 }; ListProgram output. [9, 11, 15, 18, 47, 55, 366, 420, 520, 1123]2.2. Sort List in descending orderSimilar to arrays, use Collections.reverseOrder() to reverse the default sorting behavior. //Unsorted list Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 }; ListProgram output. [1123, 520, 420, 366, 55, 47, 18, 15, 11, 9]3. Sorting a SetThere is no direct support for sorting the Set in Java. To sort a Set, follow these steps:
Program output. [9, 11, 15, 18, 47, 55, 366, 420, 520, 1123]4. Sorting a MapA Map is the collection of key-value pairs. So logically, we can sort the maps in two ways i.e. sort by key or sort by value. 4.1. Sort a Map by KeyThe best and most effective a sort a map by keys is to add all map entries in TreeMap object. TreeMap stores the keys in sorted order, always. HashMapProgram output. 4.2. Sort a Map by ValueIn Java 8, Map.Entry class has static method comparingByValue() to help us in sorting the Map by values. The comparingByValue() method returns a Comparator that compares Map.Entry in natural order on values. HashMapProgram output. {50=Alex, 60=Brian, 20=Charles, 10=David, 70=Edwin, 120=George}5. Sorting Custom ObjectsCustom objects are user defined classes which store the domain data e.g. Employee, Department, Account etc. To sort a list of custom objects, we have two popular approaches i.e. Comparable and Comparator interfaces. In given examples, we will sort a collection of Employee objects. import java.time.LocalDate; public class Employee implements Comparable5.1. Comparable interfaceComparable interface enables the natural ordering of the classes it implements. It makes the classes comparable to its other instances. A class implementing Comparable interface must override compareTo() method in which it can specify the comparison logic between two instances of same class. Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort() and Arrays.sort(). Objects that implement this interface will be automatically sorted when put in a sorted map (as keys) or sorted set (as elements). It is strongly recommended (though not required) that natural orderings be consistent with equals() method. Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals(). ArrayListProgram output. 5.2. ComparatorMany times we face situations where we do not seek natural ordering or source code unavailability for editing due to legacy code issues. In this case, we can take help of Comparator interface. Comparator does not require modifying the source code of the class. We can create the comparison logic in separate class which implement Comparator interface and override its compare() method. Then pass this comparator to sort() methods along with list of custom objects. For example, below Comparator sorts the employees list by their name. import java.util.Comparator; public class NameSorter implements ComparatorJava program to sort a list using Comparator interface implemetation. Notice the use of NameSorter in sort() method as second argument. ArrayListProgram output. [Employee [id=1, name=Alex, dob=2018-04-21], Employee [id=4, name=Brian, dob=2018-04-22], Employee [id=5, name=Charles, dob=2018-04-23], Employee [id=2, name=Pawan, dob=2018-04-24], Employee [id=3, name=Piyush, dob=2018-04-25]]5.3. Sort with Java 8 LambdaJava 8 Lambda expressions help in writing Comparator implementations on the fly. We do not need to create seperate class to provide the one time comparison logic. Comparator5.4. Group by sortingTo sort a collection of objects on different fields (groupby sort) using multiple comparators in chain. This chaining of comparators can be created using Comparator.comparing() and Comparator.thenComparing() methods. For example, we sorting the list of employees by name and then sort again by their age. ArrayListProgram output. [Employee [id=1, name=Alex, dob=2018-04-21], Employee [id=3, name=Alex, dob=2018-04-25], Employee [id=2, name=Alex, dob=2018-04-30], Employee [id=4, name=Brian, dob=2018-04-01], Employee [id=5, name=Charles, dob=2018-04-23]]6. SummaryIn the above-given examples, we learned to sort an array, list, map, and set. We saw different ways to initialize and use Comparator interface including lambda expressions. Feel free to share your thoughts on Sorting in Java. Happy Learning !! Was this post helpful?Let us know if you liked the post. Thats the only way we can improve. Yes No |