Take n random elements from a List?

后端 未结 12 1599
天涯浪人
天涯浪人 2020-11-27 16:09

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

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 16:23

    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:

    • efficient enough on random access lists like ArrayList if you don't need many elements from the source
    • doesn't modify the source
    • DOES NOT guarantee uniqueness, if it's not super important for you. If you pick 5 from a hundred, there's a very good chance the elements will be unique.

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

提交回复
热议问题