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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.