Perform operation on n random distinct elements from Collection using Streams API

前端 未结 7 1597
野趣味
野趣味 2020-12-03 17:30

I\'m attempting to retrieve n unique random elements for further processing from a Collection using the Streams API in Java 8, however, without much or any luck.

Mor

7条回答
  •  时光取名叫无心
    2020-12-03 18:12

    List collection = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    int n = 4;
    Random random = ThreadLocalRandom.current();
    
    random.ints(0, collection.size())
            .distinct()
            .limit(n)
            .mapToObj(collection::get)
            .forEach(System.out::println);
    

    This will of course have the overhead of the intermediate set of indexes and it will hang forever if n > collection.size().

    If you want to avoid any non-constatn overhead, you'll have to make a stateful Predicate.

提交回复
热议问题