Java Utility Library

Java Collections - reverse() Method



The java.util.Collections.reverse() method is used to reverse the order of the elements in the specified list.

Syntax

public static void reverse(List<?> list)

Parameters

list Specify the list whose elements are to be reversed.

Return Value

void type.

Exception

Throws UnsupportedOperationException, if the specified list or its list-iterator does not support the set operation.

Example:

In the example below, the java.util.Collections.reverse() method is used to reverse the order of elements in the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list objects
    List<Integer> MyList = new ArrayList<Integer>();

    //populating MyList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);

    //printing the MyList
    System.out.println("MyList contains: " + MyList); 

    //reverse the order of elements in the list
    Collections.reverse(MyList);

    //printing the MyList
    System.out.println("MyList contains: " + MyList); 
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40]
MyList contains: [40, 30, 20, 10]

❮ Java.util - Collections