Sorting ArrayList in descending order

In this article, we will discuss how to sort contents of ArrayList in descending order using Collections class’s utility sort() and reverseOrder() methods

 

sort() method –> to sort ArrayList contents in ascending order
reverseOrder() method –> this comparator is used to sort ArrayList contents in descending order, along with sort() method

 

To sort ArrayList contents in descending order

Method signature:

public static Comparator reverseOrder();

This method is used to sort ArrayList contents in descending order

 

SortingArrayListContentsInDescendingOrder.java

package in.bench.resources.java.collections;

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

public class SortingArrayListContentsInDescendingOrder {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> companies = new ArrayList<String>();

		// adding elements to ArrayList object
		companies.add("LinkedIn");
		companies.add("Amazon");
		companies.add("Google");
		companies.add("Apple");
		companies.add("Facebook");
		companies.add("Oracle");
		companies.add("Microsoft");

		// Iterating using enhanced for-loop
		System.out.println("Before Sorting : Insertion Order\n");
		for(String company : companies) {
			System.out.println(company);
		}


		// to sort ArrayList contents in ascending order
		Collections.sort(companies);

		// reverse order of ArrayList contents
		System.out.println("\n\n\nAfter Sorting : "
				+ "ascending order\n");
		for(String company : companies) {
			System.out.println(company);
		}


		// to reverse sort ArrayList contents
		Collections.sort(companies, Collections.reverseOrder());

		// reverse order of ArrayList contents
		System.out.println("\n\n\nAfter reverseOrder : "
				+ "descending order\n");
		for(String company : companies) {
			System.out.println(company);
		}
	}
}

Output:

Before Sorting : Insertion Order

LinkedIn
Amazon
Google
Apple
Facebook
Oracle
Microsoft



After Sorting : ascending order

Amazon
Apple
Facebook
Google
LinkedIn
Microsoft
Oracle



After reverseOrder : descending order

Oracle
Microsoft
LinkedIn
Google
Facebook
Apple
Amazon

 

 

 

References:

https://docs.oracle.com/javase/tutorial/collections/intro/
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Enumeration.html
https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html

 

Happy Coding !!
Happy Learning !!