How to reverse an ArrayList in Java?

Java 8Object Oriented ProgrammingProgramming

The Collections class provides a method named reverse() this method accepts a list and reverses the order of elements in it.

Example:

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

public class Sample {
   public static void main(String[] args){
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      Set<String> set = new LinkedHashSet<String>(list);
      System.out.println(set);
      Collections.reverse(list);
      System.out.println(list);
   }
}

Output:

[JavaFx, Java, WebGL, OpenCV]
[OpenCV, WebGL, Java, JavaFx]
raja
Published on 17-Jan-2018 10:30:38
Advertisements