How to reverse ArrayList contents

In this article, we will discuss how to reverse the contents of ArrayList using Collections class’s utility reverse() method

 

To reverse ArrayList contents :

Method signature:

public static void reverse(List list);
  • This method is used to reverse the order of ArrayList contents
  • i.e.; reverse-order of insertion-order

ReverseArrayListContents.java

package in.bench.resources.java.collections;

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

public class ReverseArrayListContents {

	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("Insertion Order: Iterating ArrayList\n");
		for(String company : companies) {
			System.out.println(company);
		}

		// to reverse ArrayList contents
		Collections.reverse(companies);

		// reverse order of ArrayList contents
		System.out.println("\n\n\nReverse Order: Iterating ArrayList\n");
		for(String company : companies) {
			System.out.println(company);
		}
	}
}

Output:

Insertion Order: Iterating ArrayList

LinkedIn
Amazon
Google
Apple
Facebook
Oracle
Microsoft



Reverse Order: Iterating ArrayList

Microsoft
Oracle
Facebook
Apple
Google
Amazon
LinkedIn

From above example, ArrayList

  • allows duplicate elements
  • null object is allowed
  • while iterating insertion-order is maintained

 

References:

 

Happy Coding !!
Happy Learning !!

Sorting ArrayList in descending order
Adding one ArrayList to another ArrayList using addAll() method