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".
4 Answers
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.
sizemethod is efficient you should useapple(randomIndexLessThanSize). In general there is no such method: for instance you can't get fair random element from infinite collection.