What is Collections.rotate in Java?

The rotate function in the Collections class is used to rotate the elements in the specified list by the specified distance. The distance can be zero, negative, or positive.

Collections is defined in the util package in Java, so you must import the util package before using the rotate function, as shown below:

import java.util.Collections;

Syntax

The syntax for rotate is shown below:

Collections.rotate(list, distance)

Method signature

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

Parameters

  • List<?> list: the list to be rotated.
  • int distance: the distance to rotate the list.

Return value

This method modifies the original list and doesn’t return anything.

Code

The code below will help you understand the rotate function better. We first define an ArrayList and populate the list using the add function. We then define the rotation distance. Using the rotate function, we rotate the elements in the list.

import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
stringList.add("d");
int distance = 3;
System.out.println("Before rotation - " + stringList);
Collections.rotate(stringList, distance);
System.out.println("After rotation - " + stringList);
}
}