Java Utility Library

Java Collections - rotate() Method



The java.util.Collections.rotate() method is used to rotate the elements in the specified list by the specified distance.

Syntax

public static void rotate(List<?> list,
                          int distance)

Parameters

list Specify the list to be rotated.
distance Specify the distance to rotate the list. There are no constraints on this value; it may be zero, negative, or greater than list.size().

Return Value

void type.

Exception

Throws UnsupportedOperationException, if the specified list or its list-iterator does not support the set operation.

Example:

In the example below, the java.util.Collections.rotate() method is used to rotate the elements of the given list by specified distance.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list objects
    List<Integer> MyList = new ArrayList<Integer>();

    //populating MyList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);
    MyList.add(50);
    MyList.add(60);

    //printing the MyList
    System.out.println("MyList contains: " + MyList);  

    //rotating the list by distance 2
    Collections.rotate(MyList, 2);

    //printing the MyList
    System.out.println("MyList contains: " + MyList);  
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40, 50, 60]
MyList contains: [50, 60, 10, 20, 30, 40]

❮ Java.util - Collections