Efficient way to get a random element in Scala?

2019-06-20 17:56发布

问题:

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".

回答1:

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.



回答2:

util.Random.shuffle(List.range(1,100)) take 3 


回答3:

Use a collection with a constant-time size() and get() method.



回答4:

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.)



标签: scala random