This post will discuss how to rotate a List in Java. Rotating a list in Java means changing the order of the elements in the list by shifting them to the left or right by a certain number of positions.

There are several ways to rotate a List in Java, depending on whether we want to use built-in methods or write our own logic. Here are some of the most common ways to rotate a list in Java:

1. Using Collections.rotate() method

The rotate() a built-in method from the java.util.Collections class that reorders the elements of a list by moving them to the right by the specified distance. If the distance is negative, the elements are moved to the left instead. This method modifies the original list and does not create a new one. For example, the following code left-rotate a list by 2 positions:

Download  Run Code

 
To right shift an array by specific positions, we can pass the negative distance to the Collections.rotate() method. For example, this code is the same as the previous method, but with a negative distance to rotate the elements to the right.

Download  Run Code

2. Using a for loop

Finally, we can implement our own custom logic for rotating a list by using a for loop and the Collections.remove() and Collections.add() methods that remove and add elements at the specified indices. We can use this method to perform either a left or right rotation by changing the direction and bounds of the loop. For example, the following code left-shifts elements in the list by specific positions:

Download  Run Code

That’s all about rotating a List in Java.