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,


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


RUN 1:
Random value of the list 102

Random value of the list 65    


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.


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.


Top MCQs

Comments and Discussions!

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

© some rights reserved.