Sort Java ArrayList in descending order

In my previous article we have learnt how to sort a arraylist in ascending order,In this example we will learn to sort in descending order using Sort() and reverseOrder() method of the Collection API. 

Code Snippet

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DescendingSortArrayList 
{
	public static void main(String args[])
	{
                //Create a new ArrayList object
		ArrayList<String> l1 = new ArrayList<String>();
		
                //Adding Elements to the list
                l1.add("String 1");
		l1.add("String 2");
		l1.add("String 3");
		
		System.out.println("****Before sorting****");
		for(String value:l1)
		{ 
			System.out.println(value);
		}
		
                //Descending order sort
		Collections.sort(l1,Collections.reverseOrder());
		
		System.out.println("****After sorting****");
		for(String value:l1)
		{ 
			System.out.println(value);
		}
	}
}

Output

****Before sorting****
String 1
String 2
String 3
****After sorting****
String 3
String 2
String 1

Leave a Reply

Your email address will not be published. Required fields are marked *