How to rotate elements of the List in Java



Problem Description

How to rotate elements of the List?

Solution

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);
   }
}

Result

The above code sample will produce the following result.

List :[one, Two, three, Four, five, six]
rotate: [Four, five, six, one, Two, three]
java_collections.htm
Advertisements