Press "Enter" to skip to content

Sort ArrayList Elements in Descending Order Java

In this article, we will see how to sort ArrayList elements in descending order using sort(List list, Collections.reverseOrder()) method.

Examples:
Input:    23, 54, 32, 56, 78, 65
Output: 78, 65, 56, 54, 32, 23

Input:    Microsoft, Vmware, Salesforce, Apple, Facebook
Output: Vmware, Salesforce, Microsoft, Facebook, Apple

Example 1:

The below programs shows how to use sort(List list,Collections.reverseOrder()) to sort ArrayList elements in descending order. Here the elements are of Integer type.

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

public class ArrayListSortDescendingExample {

	public static void main(String[] args) {
		ArrayList<Integer> numbers = new ArrayList<>();
		numbers.add(23);
		numbers.add(54);
		numbers.add(32);
		numbers.add(56);
		numbers.add(78);
		numbers.add(65);

		System.out.println("Elements before sorting : " + numbers);
		Collections.sort(numbers, Collections.reverseOrder());
		System.out.println("After sorting in descending order : " + numbers);

	}
}

Output:

Elements before sorting : [23, 54, 32, 56, 78, 65]
After sorting in descending order : [78, 65, 56, 54, 32, 23]

Example 2:

Let’s look at the program.

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

public class ArrayListSortDescendingDemo {

	public static void main(String[] args) {
		ArrayList<String> companies = new ArrayList<>();
		companies.add("Microsoft");
		companies.add("Vmware");
		companies.add("Salesforce");
		companies.add("Apple");
		companies.add("Facebook");

		System.out.println("Companies before sorting : " + companies);
		Collections.sort(companies, Collections.reverseOrder());
		System.out.println("ArrayList Elements after sorting in descending order : " + companies);
	}
}

Output:

Companies before sorting : [Microsoft, Vmware, Salesforce, Apple, Facebook]
ArrayList Elements after sorting in descending order : [Vmware, Salesforce, Microsoft, Facebook, Apple]

In this article, we saw how to use Collections.reverseOrder().

Further Reading:

ArrayList Reference.

Comments are closed.