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 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.

Free Resources