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

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

    You can use limit to solve your problem.

    http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#limit-long-

    Collections.shuffle(collection); 
    
    int howManyDoYouWant = 10;
    List smallerCollection = collection
        .stream()
        .limit(howManyDoYouWant)
        .collect(Collectors.toList());
    

提交回复
热议问题