Kotlin List randomOrNull()
Syntax & Examples
Syntax of List.randomOrNull()
There are 2 variations for the syntax of List.randomOrNull() extension function. They are:
1.
fun <T> Collection<T>.randomOrNull(): T?
This extension function returns a random element from this collection, or null if this collection is empty.
2.
fun <T> Collection<T>.randomOrNull(random: Random): T?
This extension function returns a random element from this collection using the specified source of randomness, or null if this collection is empty.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the integers[1, 2, 3, 4, 5]
. - We use the
randomOrNull()
function to get a random element from the list. - Finally, we print the random element to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val randomElement = list.randomOrNull();
println(randomElement);
}
Output
4
2 Example
In this example,
- We create a list named
list
containing the characters['a', 'b', 'c', 'd', 'e']
. - We use the
randomOrNull()
function to get a random element from the list. - Finally, we print the random element to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e');
val randomElement = list.randomOrNull();
println(randomElement);
}
Output
c
3 Example
In this example,
- We create a list named
list
containing the strings['apple', 'banana', 'cherry', 'date', 'elderberry']
. - We use the
randomOrNull()
function to get a random element from the list. - Finally, we print the random element to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val randomElement = list.randomOrNull();
println(randomElement);
}
Output
banana
Summary
In this Kotlin tutorial, we learned about randomOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.