Reverse the order of elements in the list

In this post under Java Collections, I will show with example how to reverse the elements order in a list.

Below is the complete code for your reference.

Main class

1  package core.collection;
2  
3  import java.util.ArrayList;
4  import java.util.Collections;
5  import java.util.List;
6  
7  public class ReverseListDemo {
8      public static void main(String args[]) {
9          List<Integer> integerList = new ArrayList<>(0);
10         integerList.add(1);
11         integerList.add(4);
12         integerList.add(5);
13         integerList.add(2);
14         integerList.add(3);
15 
16         System.out.println("Before reversing: " + integerList);
17 
18         Collections.reverse(integerList);
19 
20         System.out.println("After reversing: " + integerList);
21     }
22 }

In the above code, at line 9, I create an integer list and populate it afterwards.

At line 16, I print the elements before reversing it.

At line 18, I call “Collections” class static method “reverse” and pass the list as an argument. This will reverse the order of elements in the list.

In this way, we can reverse the elements in the list.

Below is the output for your reference

Output

Before reversing: [1, 4, 5, 2, 3]
After reversing: [3, 2, 5, 4, 1]

Leave a comment