What is an efficient way to get a random element from a collection in Scala? There's a related question here, but like one of the comments pointed out, "[that] question does not specify any efficiency needs".
An arbitrary collection cannot be accessed in constant time. So you need some special collection with the desired property. For instance — Vector
or Array
. See Performance Characteristics of collections for others.
util.Random.shuffle(List.range(1,100)) take 3
Use a collection with a constant-time size() and get() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With