Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Collections.reverse in Java?

abhilash

The reverse function of the Collections class is used to reverse the order of elements in a specified list. Collections is defined in the util package in Java, so you must import the util package before you can use the reverse function, as shown below.

import java.util.Collections;

Syntax

The syntax for the reverse function is shown below.

Collections.reverse(list)

Method signature

public static void reverse(List<?> list)

Parameter

List<?> list: the list which has to be reversed.

Return value

The method reverses the list in place and so it does not return anything.

Code

The example below will help you understand the reverse function better. We first define a list and populate the list with elements. Next, we use the reverse function to reverse the order of elements in the list.

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

public class Main {

    public static void main(String[] args){
        List<String> stringList = new ArrayList<>();
        stringList.add("One");
        stringList.add("Two");
        stringList.add("Three");
        System.out.println("List before reversal - " + stringList);
        Collections.reverse(stringList);
        System.out.println("List after reversal - " + stringList);
    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring