Home »
Code Examples »
Scala Code Examples
Scala - How to get a random element from a list of elements? Code Example
The code for How to get a random element from a list of elements?
// Importing library
import scala.util.Random
object Example {
def main(args: Array[String]) = {
// Defining a list
val cities = List(
"New Delhi",
"Mumbai",
"Chennia",
"Banglore",
"Bhopal",
"Manglore",
"Kerala"
)
// Creating a new random variable
val random = new Random
// Getting a random elements and printing it
var result = cities(random.nextInt(cities.length))
println(result)
result = cities(random.nextInt(cities.length))
println(result)
result = cities(random.nextInt(cities.length))
println(result)
}
}
/*
Output:
RUN 1:
Banglore
Banglore
Chennia
RUN 2:
Bhopal
Manglore
Mumbai
*/
Code by IncludeHelp,
on August 13, 2022 22:23