What is collections.reverse() in Java with Examples?

The java.util.Collections.reverse() method is a java.util.Collections class method. It reverses the order of the elements in the list passed as a parameter.

In Java, collections.reverse() is a method that reverses the order of elements in a given list. This method is defined in the Collections class, which is a part of the Java Collections Framework. The reverse() method takes a list as its argument and returns the same list in reverse order. The original list is modified and returned.

Here is an example of how to use collections.reverse()

 

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

public class ReverseExample {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>();
        list.add("apple");
        list.add("banana");
        list.add("orange");
        System.out.println("Original List: " + list);
        Collections.reverse(list);
        System.out.println("Reversed List: " + list);
    }
}

In this example, we create an ArrayList of strings containing the elements "apple", "banana", and "orange". We then print the original list and apply collections.reverse() to it. Finally, we print the reversed list.

The output of this program will be: 

 

Original List: [apple, banana, orange]
Reversed List: [orange, banana, apple]

As you can see, the order of the elements in the list is reversed. This method is useful when you need to reverse the order of elements in a list without manually iterating through the list and swapping elements.

Submit Your Programming Assignment Details