Rotate a List in Java

Java 8Object Oriented ProgrammingProgramming

To rotate a list in Java, let us first create a List and add elements −

List < Integer > list = new ArrayList < Integer > ();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
list.add(25);
list.add(30);
list.add(35);
list.add(40);
list.add(45);

Now, rotate the list −

Collections.reverse(list);

Example

 Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) {
      List<Integer>list = new ArrayList<Integer>();
      list.add(5);
      list.add(10);
      list.add(15);
      list.add(20);
      list.add(25);
      list.add(30);
      list.add(35);
      list.add(40);
      list.add(45);
      System.out.println("Initial list = "+list);
      Collections.reverse(list);
      System.out.println("List after rotation = "+list);
   }
}

Output

Initial list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
List after rotation = [45, 40, 35, 30, 25, 20, 15, 10, 5]
raja
Published on 25-Apr-2019 09:00:04
Advertisements