Skip to content
DeveloperMemos

Getting a Random List Item in Kotlin

Kotlin, Random, List1 min read

Working with lists is a common task in Kotlin programming, and sometimes you may need to retrieve a random item from a list. This can be useful in various scenarios, such as generating random content or selecting a winner from a participant list. In this article, we will explore different approaches to achieve this in Kotlin.

Using the random() Function

Kotlin provides a helpful extension function called random() that can be used with collections to obtain a random element. Here's an example:

1val list = listOf("Apple", "Banana", "Orange", "Mango")
2val randomItem = list.random()
3println(randomItem)

In this code snippet, we have a list of fruits, and list.random() returns a random fruit from the list. The selected item is then printed using println().

Generating a Random Index

Alternatively, you can generate a random index within the range of the list size and access the element at that index. Here's an example:

1val list = listOf("Red", "Green", "Blue", "Yellow")
2val randomIndex = (0 until list.size).random()
3val randomItem = list[randomIndex]
4println(randomItem)

In this example, we use the random() function on a range from 0 to list.size (exclusive) to obtain a random index. Then, we access the element at that index in the list.

Extension Function for Random Item

To make it more convenient, you can create an extension function on the List class to directly retrieve a random item. Here's how you can define such a function:

1fun <T> List<T>.randomItem(): T {
2 val randomIndex = (0 until size).random()
3 return get(randomIndex)
4}

Now, you can use this extension function on any list to get a random item:

1val list = listOf(1, 2, 3, 4, 5)
2val randomItem = list.randomItem()
3println(randomItem)

By calling list.randomItem(), you will receive a random item from the list, simplifying the code and making it more readable.

Conclusion

Retrieving a random item from a list is a common requirement in Kotlin programming. In this article, we explored different techniques to accomplish this task. Whether you choose to use the random() function, generate a random index, or create an extension function, you now have the necessary tools to implement this functionality efficiently in your Kotlin projects.