Get a random item from list using kotlin streams

Kotlin 1.3 and above:

Kotlin 1.3 is now available with Multiplatform Random Number Generator!
You can use it like this :

import kotlin.random.Random

fun main() {
    println(Random.nextBoolean())
    println(Random.nextInt())
}

Try it online!

or in your case

fun main() {
    val list = (1..9).filter { it % 2 == 0 }
    println(list.random())
}

Try it online!


Kotlin 1.2

Since Kotlin 1.2, we have Iterable.shuffled(). This method could help you with the use of List.take() to extract the number of element you want (only one in this example).

val list = (1..9).filter { it % 2 == 0 }
return list.shuffled().take(1)[0]

This method is less optimized than before 1.2 one but it work on multiplatform context. Use the one you need according to your context.


Before Kotlin 1.2

Before Kotlin 1.2, no solution exists on a Multiplatform context to generate Random Number. The most easy solution is to call the Platform Random directly.

JVM

On the JVM we use Random or even ThreadLocalRandom if we’re on JDK > 1.6.

import java.util.Random

fun IntRange.random() = Random().nextInt((endInclusive + 1) - start) + start

JS

On the JS, we use Math.Random.

fun IntRange.random() = (Math.random() * ((endInclusive + 1) - start) + start).toInt()

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)