Java Rotate elements with rotate()


The Collections algorithms includes a typical method rotate() that rotates the elements in cyclic order. After the last few elements, the first elements can be moved. This method is useful to change the order of elements. Note, it is not swapping or shuffling. In shuffling, elements are moved in between randomly. But here, only the order of elements is changed; what elements should come later than the other. You get better idea when you go through the following program.

Following is the method signature

  • static void rotate(List list1, int dist1): Rotates the elements in the list list1 by the specified distance dist1.

The method takes two parameters. – the list object and the distance from where rotation is required.

Example on Java Rotate elements with rotate()
import java.util.*;
public class CollectionsRotate
{
  public static void main(String args[])
  {
    ArrayList myList = new ArrayList();
    myList.add(10);      myList.add(20);
    myList.add(30);      myList.add(40);
    myList.add(50);      myList.add(60);
    System.out.println("Elements myList before rotate: " + myList);

    Collections.rotate(myList, 3);
    System.out.println("Elements myList after rotate: " + myList);
  }
}

Java Rotate elements with rotate()
Output screenshot on Java Rotate elements with rotate()

ArrayList myList = new ArrayList();
myList.add(10);

An ArrayList object myList is created and added with 6 elements.

Collections.rotate(myList, 3);

The rotate advances by two positions towards the end (actually it is 3rd, as index starts from 0). That is, elements are rotated from actual 4th to the end and in continuation 1st to 3rd. Observe the screenshot.

That is, The rotation is done from 3rd element (it is actually 4th as index starts from zero). That is first 3, 4 and 5 elements are moved and later followed by 0, 1, 2.

Leave a Comment

Your email address will not be published.