How to get a random element from a Set in Scala

elm picture elm · Jul 31, 2014 · Viewed 14.1k times · Source

For any given set, for instance,

val fruits = Set("apple", "grape", "pear", "banana")

how to get a random element from fruits ?

Many Thanks.

Answer

Govind Singh picture Govind Singh · Jul 31, 2014

convert into Vector and get random element from it

scala> val fruits = Set("apple", "grape", "pear", "banana")
fruits: scala.collection.immutable.Set[String] = Set(apple, grape, pear, banana)

scala> import scala.util.Random
import scala.util.Random

scala> val rnd=new Random
rnd: scala.util.Random = scala.util.Random@31a9253

scala> fruits.toVector(rnd.nextInt(fruits.size))
res8: String = apple