Java Examples - Rotate elements in a list


Problem Description:

How to rotate elements of the List?


Following example uses rotate() method to rotate elements of the list depending on the 2nd argument of the method.

import java.util.*;

public class Main {
   public static void main(String[] args) {
      List list = Arrays.asList("one Two three Four five 
      six".split(" "));
      System.out.println("List :"+list);
      Collections.rotate(list, 3);
      System.out.println("rotate: " + list);


The above code sample will produce the following result.

List :[one, Two, three, Four, five, six]
rotate: [Four, five, six, one, Two, three]