Reverse order of all elements of ArrayList with Java Collections

Java 8Object Oriented ProgrammingProgramming

In order to reverse order of all elements of ArrayList with Java Collections, we use the Collections.reverse() method.

Declaration −The java.util.Collections.reverse method is declared as follows −

public static void reverse(List<?> list)

Let us see a program to reverse order of all elements of ArrayList with Java Collections −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(1);
      list.add(2);
      list.add(7);
      list.add(8);
      list.add(3);
      list.add(9);
      System.out.println("Original list : " + list);
      Collections.reverse(list); // reversing the list
      System.out.println("Reversed list : " + list);
   }
}

Output

Original list : [1, 2, 7, 8, 3, 9]
Reversed list : [9, 3, 8, 7, 2, 1]
raja
Published on 08-Jan-2019 13:19:41
Advertisements