Home »
Scala
Getting a random element from a list of elements in Scala
By IncludeHelp Last updated : October 20, 2024
Getting a random element from a list
We can access a random element from a list in Scala using the random variable. To use the random variable, we need to import the Random class.
Step 1: Importing the Random class
import.scala.util.Random
Step 2: Create a random variable
val random_var = new Random
Step 3: Accessing random element in list
value = list(random_var.nextInt(list.length))
Example to get a random element from a list
Let's take an example to get a random element from a list in Scala,
import scala.util.Random
object MyClass {
def main(args: Array[String]) {
val list = List(12, 65, 89, 41, 99, 102)
val random = new Random
println("Random value of the list " + list(random.nextInt(list.length)))
}
}
Output
RUN 1:
Random value of the list 102
RUN2:
Random value of the list 65
Explanation
Here, we will find the random value from the list. The code looks a bit more stuffed so let's break the extracting process of random value so that it can be easily understandable.
list(random.nextInt(list.length))
This will extract a random value from the list. So, what we have done is accessing the random index of the list which is done by random.nextInt(list.length). In this, the nextInt() method of Random class is accessed which takes the limits and returns a random value.