In the previous article, we have seen Java Program to Make the ArrayList Read Only
In this article we are going to see how we can sort an ArrayList in descending order in Java programming language.
Java Program to Sort ArrayList in Reverse Order
To sort the arraylist we will be using the sort library function from the Collections class.
Approach:
- Create an arraylist
- Add some elements to the list
- Display the arraylist
- Pass the arraylist into the
sort( )
function asĀCollections.reverseOrder()
parameter to sort in descending order. - Print the new arraylist
Program:
import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { // Creating an empty ArrayList ArrayList<String> arr = new ArrayList<String>(); // Adding elements to the arrayList arr.add("One"); arr.add("Two"); arr.add("Three"); arr.add("A1"); arr.add("B2"); arr.add("C3"); // Displaying the list System.out.println("Original Arraylist"+arr); // using the sort function from collection with reverse parameter Collections.sort(arr,Collections.reverseOrder()); // Printing the modified arraylist System.out.println("After sorting in decreasing order "+arr); } }
Output: Original Arraylist[One, Two, Three, A1, B2, C3] After sorting in decreasing order [Two, Three, One, C3, B2, A1]
Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.
Related Java Programs: