How to Reverse order of elements in ArrayList

In this article, we will discuss how to reverse order of elements in List using Collections class’s utility reverse() method

 

Reversing order of elements of Java ArrayList

Method signature:

public static void reverse(List<Object> list);

ReverseArrayListContents.java

package in.bench.resources.java.collection;

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> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Narayan Murthy");
		al.add("Dinesh");  
		al.add("Nandan Nilekeni");  
		al.add("Ashok Arora");
		al.add("Shibulal");
		al.add("Kris Gopalakrishnan");
		al.add("Raghavan");

		System.out.println("Insertion order:"
				+ " Iterating ArrayList values\n");

		// Iterating using enhanced for-loop
		for(String str : al){
			System.out.println(str);
		}


		// reverse ordering of ArrayList 
		// using Collections.reverse(al);
		Collections.reverse(al);


		System.out.println("\n\nReverse Insertion order:"
				+ " after reversing using Collections.reverse(al)\n");

		// Iterating using enhanced for-loop
		for(String str : al){
			System.out.println(str);
		}
	}
}

Output:

Insertion order: Iterating ArrayList values

Narayan Murthy
Dinesh
Nandan Nilekeni
Ashok Arora
Shibulal
Kris Gopalakrishnan
Raghavan


Reverse Insertion order: after reversing using Collections.reverse(al)

Raghavan
Kris Gopalakrishnan
Shibulal
Ashok Arora
Nandan Nilekeni
Dinesh
Narayan Murthy

 

References:

 

Happy Coding !!
Happy Learning !!

How to Reverse order of Comparator
Searching element from ArrayList using Binary Search Algorithm