To shuffle a list in Kotlin, you can use the shuffle
method provided by the Kotlin standard library.
In this example,
numbers
with integer values.shuffle
method on the list object numbers
.shuffle
method randomly rearranges the elements in the list in place.fun main(args: Array<String>) {
val numbers = mutableListOf(1, 2, 3, 4, 5)
numbers.shuffle()
println("Shuffled list: $numbers")
}
Shuffled list: [3, 1, 5, 4, 2]
In this example,
words
with string values.shuffle
method on the list object words
.shuffle
method randomly rearranges the elements in the list in place.fun main(args: Array<String>) {
val words = mutableListOf("apple", "banana", "cherry", "date", "elderberry")
words.shuffle()
println("Shuffled list: $words")
}
Shuffled list: [cherry, elderberry, apple, banana, date]
In this tutorial, we learned How to Shuffle a List in Kotlin language with well detailed examples.