How to Reverse Elements Order of Java ArrayList


Here this example aims to reverse the order of all elements of ArrayList by reverse method in Java.

Source Code

package com.beginner.examples;

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

public class ReverseArrayListExample {

	public static void main(String[] args) {

		ArrayList al = new ArrayList();

		al.add("1");
		al.add("2");
		al.add("3");
		al.add("4");
		al.add("5");
		al.add("6");

		System.out.println("al:" + al);

		// Use the reverse() method of the Collections utility class to do the
		// reverse
		Collections.reverse(al);

		System.out.println("After the reversal:" + al);

	}

}

Output:

al:[1, 2, 3, 4, 5, 6]
After the reversal:[6, 5, 4, 3, 2, 1]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments