Kotlin Set shuffled()
Syntax & Examples
Set.shuffled() extension function
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.
Syntax of Set.shuffled()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
random | required | The Random instance to be used as the source of randomness. |
Return Type
Set.shuffled() returns value of type List
.
✐ Examples
1 Shuffling a set of integers
Using shuffled() to shuffle the elements in a set of integers.
For example,
- Create a set of integers.
- Use shuffled() with a Random instance to shuffle the elements.
- Print the resulting shuffled list.
Kotlin Program
import kotlin.random.Random
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val shuffledNumbers = numbers.shuffled(Random)
println(shuffledNumbers)
}
Output
[2, 5, 1, 4, 3]
2 Shuffling a set of strings
Using shuffled() to shuffle the elements in a set of strings.
For example,
- Create a set of strings.
- Use shuffled() with a Random instance to shuffle the elements.
- Print the resulting shuffled list.
Kotlin Program
import kotlin.random.Random
fun main() {
val strings = setOf("one", "two", "three")
val shuffledStrings = strings.shuffled(Random)
println(shuffledStrings)
}
Output
[three, one, two]
3 Shuffling a set of custom objects
Using shuffled() to shuffle the elements in a set of custom objects.
For example,
- Create a data class.
- Create a set of custom objects.
- Use shuffled() with a Random instance to shuffle the elements.
- Print the resulting shuffled list.
Kotlin Program
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)
}
Output
[Person(name=Bob, age=25), Person(name=Alice, age=30), Person(name=Charlie, age=35)]
Summary
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.