How to use the randomOrNull() method of ArrayList in Kotlin
Overview
The randomOrNull() method is used to return a random element from the ArrayList. If the list is empty, then null is returned.
Syntax
fun <T> Collection<T>.randomOrNull(): T?
Parameter
This method doesn’t take any arguments.
Return value
This method returns a random element from the list if the list is not empty. Otherwise, it returns a null value.
Code example
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}")}
Code explanation
-
Lines 3–6: We create a new ArrayList with the name
listand add three elements to it, using theaddmethod. The list is now[1,2,3]. -
Line 9: We use the
randomOrNullmethod to get a random element from thelist. This method returns a random element from thelist. -
Line 12: We assign an empty
ArrayListas a value to thelistvariable. -
Line 14: We use the
randomOrNullmethod to get a random element from thelist. This method returns anullvalue, because thelistis empty.