Issue
How can I take n random elements from an ArrayList<E>? Ideally, I'd like to be able to make successive calls to the take() method to get another x elements, without replacement.
Solution
Two main ways.
Use
Random#nextInt(int):List<Foo> list = createItSomehow(); Random random = new Random(); Foo foo = list.get(random.nextInt(list.size()));It's however not guaranteed that successive
ncalls returns unique elements.-
List<Foo> list = createItSomehow(); Collections.shuffle(list); Foo foo = list.get(0);It enables you to get
nunique elements by an incremented index (assuming that the list itself contains unique elements).
In case you're wondering if there's a Java 8 Stream approach; no, there isn't a built-in one. There's no such thing as Comparator#randomOrder() in standard API (yet?). You could try something like below while still satisfying the strict Comparator contract (although the distribution is pretty terrible):
List<Foo> list = createItSomehow();
int random = new Random().nextInt();
Foo foo = list.stream().sorted(Comparator.comparingInt(o -> System.identityHashCode(o) ^ random)).findFirst().get();
Better use Collections#shuffle() instead.
Answered By - BalusC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.