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