Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Reverse a List


As we have seen the implementations of a List are :

  1. ArrayList

  2. LinkedList


Let us see the ArrayList implementation


How to reverse a List?


Reversal of a List can be done using Collections.reverse() method. It is independent of the alphabets. And is not a sort. It is just a reversal.


Example :



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

public class MyApplication {
    public static void main(String[] args) {

        List x = new ArrayList<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");

        Collections.reverse(x);

        for (String data : x) {
            System.out.println(data);
        }
    }
}


Output :



  Salim
  Kriti
  Mohan

So, in the above code we have created a List,


List x = new ArrayList<>();

And initialised three names to the variable x,


x.add("Mohan");
x.add("Kriti");
x.add("Salim");

Below is how the values are positioned in the List,

Spring_Boot

Then we have used the Collections.reverse(x) Method to reverse the elements of the List x.


Collections.reverse(x);

And the List x gets sorted in reverse order with Salim as the first value, Mohan second and Kriti as the third.

Spring_Boot

And we get the below output.

Output :



  Salim
  Kriti
  Mohan

Note : The same code applies for LinkedList as well. Just that you need to replace ArrayList LinkedList.