Getting a random element from a list of elements in Scala

Here, we are going to learn how to get a random element from a list of elements in Scala?
Submitted by Shivang Yadav, on May 11, 2020

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.

Importing the Random class,

    import.scala.util.Random    

Create a random variable,

    val random_var = new Random

Accessing random element in list,

    value = list(random_var.nextInt(list.length))

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.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.