The java.util Collections class provides a method named rotate, which is used to rotate the elements in a list by a specified distance. This method can be used to shift all the elements in the list towards the left or right.
Syntax:
public static void rotate(List list, int distance)
Here, "list" refers to the list whose elements are to be rotated, and "distance" specifies the number of positions to shift the elements.
Example 1: Rotate a list to the right by 3 positions
List numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); Collections.rotate(numbers, 3); System.out.println(numbers);
Output: [3, 4, 5, 1, 2]
Example 2: Rotate a list to the left by 2 positions
List names = new LinkedList<>(Arrays.asList("Alice", "Bob", "Charlie", "David")); Collections.rotate(names, -2); System.out.println(names);
Output: [Charlie, David, Alice, Bob]
This method belongs to the java.util package in the standard Java library.
Java Collections.rotate - 21 examples found. These are the top rated real world Java examples of java.util.Collections.rotate extracted from open source projects. You can rate examples to help us improve the quality of examples.