Pick multiple random elements from a list in Java
Try this:
public static List<String> pickNRandom(List<String> lst, int n) {
List<String> copy = new ArrayList<String>(lst);
Collections.shuffle(copy);
return n > copy.size() ? copy.subList(0, copy.size()) : copy.subList(0, n);
}
I'm assuming that there are no repeated elements in the input list, also I take the precaution of shuffling a copy for leaving the original list undisturbed. Use it like this:
List<String> randomPicks = pickNRandom(teamList, 3);
You can also use reservoir sampling.
It has the advantage that you do not need to know the size of the source list in advance (e.g. if you are given an Iterable
instead of a List
.) Also it is efficient even when the source list is not random-access, like the LinkedList
in your example.
The shuffle
approach is the most idiomatic: after that, first K elements are exactly what you need.
If K is much less than the length of the list, you may want to be faster. In this case, iterate through the list, randomly exchanging the current element with itself or any of the elements after it. After the K-th element, stop and return the K-prefix: it will be already perfectly shuffled, and you don't need to care about the rest of the list.
(obviously, you'd like to use ArrayList
here)
Create a set of ints, and put random numbers between 0 and list's length minus one into it in a loop, while the size of the set is not equal the desired number of random elements. Go through the set, and pick list elements as indicated by the numbers in the set. This way would keep your original list intact.