Kotlin Tutorials

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

ParameterOptional/RequiredDescription
randomrequiredThe 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,

  1. Create a set of integers.
  2. Use shuffled() with a Random instance to shuffle the elements.
  3. 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,

  1. Create a set of strings.
  2. Use shuffled() with a Random instance to shuffle the elements.
  3. 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,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use shuffled() with a Random instance to shuffle the elements.
  4. 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.