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

前端 未结 7 1625
野趣味
野趣味 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:14

    It should be clear that streaming the collection is not what you want.

    Use the generate() and limit methods:

    Stream.generate(() -> list.get(new Random().nextInt(list.size())).limit(3).forEach(...);
    

提交回复
热议问题