The randomOrNull()
method is used to return a random element from the ArrayList. If the list is empty, then null
is returned.
fun <T> Collection<T>.randomOrNull(): T?
This method doesn’t take any arguments.
This method returns a random element from the list if the list is not empty. Otherwise, it returns a null
value.
The code given below demonstrates how we can use the randomOrNull()
method:
fun main() { var list = ArrayList<Int>() list.add(1) list.add(2) list.add(3) println("The list is $list") var randElement = list.randomOrNull() println("Random element from the list ${randElement}") list = ArrayList<Int>(); println("\nThe list is $list") randElement = list.randomOrNull() println("Random element from the list ${randElement}") }
Lines 3–6: We create a new ArrayList with the name list
and add three elements to it, using the add
method. The list is now [1,2,3]
.
Line 9: We use the randomOrNull
method to get a random element from the list
. This method returns a random element from the list
.
Line 12: We assign an empty ArrayList
as a value to the list
variable.
Line 14: We use the randomOrNull
method to get a random element from the list
. This method returns a null
value, because the list
is empty.
RELATED TAGS
CONTRIBUTOR
View all Courses