Randomly select an item from a List in Kotlin
This article explores different ways to randomly select an item from a List in Kotlin.
1. Using random() function
Since Kotlin 1.3, you can use the random() function to return a random element from a list. A typical invocation for this method would look like below. Note that it throws NoSuchElementException if the list is empty.
|
1 2 3 4 5 6 |
fun main() { val values = (1.. 10).toList() val random = values.random() println(random) } |
2. Using Random.nextInt() function
Before Kotlin 1.3, you can generate a random index and use that index to get the random value. This can be achieved using the Random.nextInt() function, which returns a random value uniformly distributed between 0 (inclusive) and the specified bound (exclusive).
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import kotlin.random.Random fun <T> getRandomElement(list: List<T>): T { val randomIndex = Random.nextInt(list.size) return list[randomIndex] } fun main() { val values = (1.. 10).toList() val random = getRandomElement(values) println(random) } |
3. Using shuffled() function
Another solution is to randomize the list using the shuffled() function, and return the value present at the first or the last index. This would translate to a simple code below:
|
1 2 3 4 5 |
fun main() { val values = (1.. 10).toList() val random = values.shuffled()[0] println(random) } |
That’s all about randomly selecting an item from a List in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)