Search

Dark theme | Light theme

April 3, 2026

Kotlin Kandy: Get A Random Element From A Collection

Kotlin has very useful extensions functions for working with collections. These extension functions make working with collections more easy and fun. One of the extension functions is the random function. When you call random() Kotlin returns a single element from the collection using the default random source. The function also accepts a Random instance as argument. This instance has a seeded value to return repeatable random values.

In the following example you can see different ways to use random on collections:

import kotlin.random.Random

val languages = listOf("Kotlin", "Groovy", "Java", "Scala")

// Calling random() without arguments uses the default random source.
val language = languages.random()
assert(language in languages)


// When you use the same seed you get the same result.
assert(languages.random(Random(42)) == "Kotlin")
assert(languages.random(Random(42)) == "Kotlin")


// Reusing the same Random instance gives you a repeatable sequence
// of random values.
val randomLanguages = Random(123)
val picks = List(5) { languages.random(randomLanguages) }

assert(picks == listOf("Kotlin", "Groovy", "Scala", "Groovy", "Kotlin"))


// A Set is also a collection, so random works here as well.
val colors = setOf("red", "green", "blue", "yellow")
assert(colors.random(Random(42)) == "red")


// You can also use random on Map.entries.
val tools = mapOf(
    "build" to "Gradle",
    "http" to "Ktor"
)

assert(tools.entries.random(Random(42)).toPair() == ("build" to "Gradle"))


// Calling random() on an empty collection throws a NoSuchElementException.
val failure = runCatching { emptyList<String>().random() }
assert(failure.exceptionOrNull() is NoSuchElementException)

Written with Kotlin 2.3.20.