How can I take n random elements from an ArrayList? Ideally, I\'d like to be able to make successive calls to the take() method to get an
As noted in other answers, Collections.shuffle is not very efficient when the source list is big, because of the copying. Here is a Java 8 one-liner that:
Code:
private static List pickRandom(List list, int n) {
return new Random().ints(n, 0, list.size()).mapToObj(list::get).collect(Collectors.toList());
}
However, for a list with no quick random access (like LinkedList) the complexity would be n*O(list_size).