Get random elements from lists

Sometimes we may need to get a number of random elements from lists. To do this, we can use a function to get the indices of these elements first.

The function getIndices takes two parameters: num is the number of elements to get, max is the maximum value of index.

1
2
3
4
5
6
7
8
9
import java.util.concurrent.ThreadLocalRandom

fun getIndices(num: Int, max: Int): Set<Int> {
val results = mutableSetOf<Int>()
while (results.size < num) {
results.add(ThreadLocalRandom.current().nextInt(max))
}
return results
}

The function getRandomElements in the code below gets the list of selected elements.

1
2
3
4
fun <T> getRandomElements(list: List<T>, num: Int): List<T> {
val indices = getIndices(Math.min(num, list.size), list.size)
return indices.map { list[it] }
}

We can invoke getRandomElements as below.

1
getRandomElements(listOf(1, 2, 3), 2)
Comments