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".
Asked
Active
Viewed 2,807 times
5
-
1In case `size` method is efficient you should use `apple(randomIndexLessThanSize)`. In general there is no such method: for instance you can't get fair random element from infinite collection. – senia Sep 07 '13 at 15:59
4 Answers
6
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.

Arseniy Zhizhelev
- 2,381
- 17
- 21
1
If you need random order of all collection elements, then Random.shuffle
is what you need. (You'd better convert the original collection to array to avoid forward and backward conversion.)

Arseniy Zhizhelev
- 2,381
- 17
- 21