In this tutorial, you will learn how to sort an ArrayList in descending order.
Example 1: Sorting an ArrayList in Descending order
We are using Collections.reverseOrder()
method along with Collections.sort()
in order to sort the list in decreasing order. In this example, we are using the following statement for sorting the list in reverse order.
Collections.sort(arraylist, Collections.reverseOrder());
You can also sort an ArrayList in descending order like this. This way the list will be sorted in ascending order first and then it will be reversed.
Collections.sort(list); Collections.reverse(list);
Source code:
In this example, we have an ArrayList of string type. We have added few elements to it using add() method, we are sorting the ArrayList using Collections.sort()
. In the end, we are printing the sorted ArrayList.
import java.util.*; public class JavaExample { 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 sorted the ArrayList
of String type (ArrayList<String>
), the logic is same for other type of ArrayList as well.
Example 2: Sorting an ArrayList in descending order using Collections.reverse()
import java.util.*; public class JavaExample { public static void main(String args[]){ ArrayList<String> arrList = new ArrayList<String>(); arrList.add("Chaitanya"); arrList.add("BeginnersBook"); arrList.add("Tutorials"); arrList.add("Website"); /*Unsorted List: ArrayList content before sorting*/ System.out.println("Before Sorting:"); for(String str: arrList){ System.out.println(str); } // Sorting in decreasing order Collections.sort(arrList); //sorting in ascending order Collections.reverse(arrList); //reversing the sorted list // print sorted arraylist System.out.println();//new line System.out.println("After sorting: "); for(String str: arrList){ System.out.println(str); } } }
Output:
Before Sorting: Chaitanya BeginnersBook Tutorials Website After sorting: Website Tutorials Chaitanya BeginnersBook
Recommended Articles:
Amisha says
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. :)
Hassan Jamil says
Very helpful, saved my time.
Dipak Rai says
Thank You, Thumbs Up!