Earlier we shared the examples of ArrayList sorting in ascending order. Here we will learn how to sort an ArrayList in descending (or decreasing) order.
Example: Sorting in Descending order
We are using Collections.reverseOrder()
method along with Collections.sort()
in order to sort the list in decreasing order. In the below example we have used the following statement for sorting in reverse order.
Collections.sort(arraylist, Collections.reverseOrder());
However the reverse order sorting can also be done as following – This way the list will be sorted in ascending order first and then it will be reversed.
Collections.sort(list);
Collections.reverse(list);
Complete example:
import java.util.*; public class Details { public static void main(String args[]){ ArrayList<String> arraylist = new ArrayList<String>(); arraylist.add("AA"); arraylist.add("ZZ"); arraylist.add("CC"); arraylist.add("FF"); /*Unsorted List: ArrayList content before sorting*/ System.out.println("Before Sorting:"); for(String str: arraylist){ System.out.println(str); } /* Sorting in decreasing order*/ Collections.sort(arraylist, Collections.reverseOrder()); /* Sorted List in reverse order*/ System.out.println("ArrayList in descending order:"); for(String str: arraylist){ System.out.println(str); } } }
Output:
Before Sorting: AA ZZ CC FF ArrayList in descending order: ZZ FF CC AA
In the above example we have used the ArrayList
of String type (ArrayList<String>
) for sorting. The same sorting method can be used for the list of integers as well.
Though Collections is one of the most interesting part of java, was not satisfied with any sites I have visited so far. Must say, the collection section of your website is just a wonderful door to understanding the collections in the most subtle way. Thanks a lot :) Each and every section is just very nicely explained. :)
Very helpful, saved my time.
Thank You, Thumbs Up!