This article explores different ways to rotate a list in Kotlin.

1. Using Collections.rotate() function

To rotate a list by some position, use the built-in static function Collections.rotate(). The following code example shows invocation for this function, where the code left-rotated a list by 2 positions.

Download Code

 
To right-shift the list, pass the negative position to the Collections.rotate() function. For example, passing -2 will right-rotate a list by 2 positions, as shown below:

Download Code

2. Using drop() + take() function

Alternatively, you can write your own extension function on MutableList<T>. To left-rotate a list by specified positions, you can use drop() with take() library function. And to right-rotate a list by specified positions, use takeLast() with dropLast() library function.

Download Code

3. Using Loop

You can write your custom logic for rotating a list. For example, the following code left-shifts elements in the list by specific positions. The code can be easily modified to right-shift a list.

Download Code

That’s all about rotating a list in Kotlin.