How to reverse a List in Java

The order of the Objects in a list can be reversed using the reverse method of Collections utility class.

Syntax:

Collections.reverse( list );

Here is an example creating a list with 4 values: a, b, c and d. It is using the class Arrays asList to create the typed List. The list is then written in the output to show the starting order. The order is then reversed calling the method reverse from the Collections Object of the util package. Finally, the updated list is written in the output to show the new order. The list used for this example is a List of Strings, the Arrays class created the list automatically without passing an implementation.

Create the following java file:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseList {

    public static void main(String[] argv) {
	
	List<String> list = Arrays.asList("a", "b", "c", "d");
        System.out.println( "Before reverse: " + list );

        // Reverse the order
        Collections.reverse( list );
        
        System.out.println( "After reverse: " +list );
    }

}

It is recommended to use the implementation from a library instead of implementing a new version of a method. It ensures the code is simpler, easier to read and it is a method that is maintained by outside resources.

The output will be:

Before reverse: [a, b, c, d]
After reverse: [d, c, b, a]

References:

Class Collections Javadoc

Share this article:

Recent Comments