The shuffled() extension function in Kotlin returns a new list with the elements of the original list randomly shuffled using the specified random instance as the source of randomness.
The syntax of Set.shuffled() extension function is:
fun <T> Set<T>.shuffled(random: Random): List<T>
This shuffled() extension function of Set returns a new list with the elements of this list randomly shuffled using the specified random instance as the source of randomness.
Parameter | Optional/Required | Description |
---|---|---|
random | required | The Random instance to be used as the source of randomness. |
Set.shuffled() returns value of type List
.
Using shuffled() to shuffle the elements in a set of integers.
For example,
import kotlin.random.Random
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val shuffledNumbers = numbers.shuffled(Random)
println(shuffledNumbers)
}
[2, 5, 1, 4, 3]
Using shuffled() to shuffle the elements in a set of strings.
For example,
import kotlin.random.Random
fun main() {
val strings = setOf("one", "two", "three")
val shuffledStrings = strings.shuffled(Random)
println(shuffledStrings)
}
[three, one, two]
Using shuffled() to shuffle the elements in a set of custom objects.
For example,
import kotlin.random.Random
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val shuffledPeople = people.shuffled(Random)
println(shuffledPeople)
}
[Person(name=Bob, age=25), Person(name=Alice, age=30), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about shuffled() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.