To rotate elements in a list in Kotlin, you can use the slice
and plus
methods of the List class.
In this example,
list
with the values 1, 2, 3, 4, and 5.n
to specify the number of positions to rotate the list.slice
method to get the sublist from the n
-th position to the end of the list.slice
method again to get the sublist from the beginning of the list to the n
-th position.plus
operator to create the rotated list.fun main() {
val list = listOf(1, 2, 3, 4, 5)
val n = 2
val rotatedList = list.slice(n until list.size) + list.slice(0 until n)
println("Rotated list: $rotatedList")
}
Rotated list: [3, 4, 5, 1, 2]
In this example,
list
with the values "apple", "banana", "cherry", "date", and "elderberry".n
to specify the number of positions to rotate the list.slice
method to get the sublist from the n
-th position to the end of the list.slice
method again to get the sublist from the beginning of the list to the n
-th position.plus
operator to create the rotated list.fun main() {
val list = listOf("apple", "banana", "cherry", "date", "elderberry")
val n = 3
val rotatedList = list.slice(n until list.size) + list.slice(0 until n)
println("Rotated list: $rotatedList")
}
Rotated list: [date, elderberry, apple, banana, cherry]
In this tutorial, we learned How to Rotate Elements in a List in Kotlin language with well detailed examples.