I have a set of unique elements (there are not two identical elements). And I would like to extract N random and different elements from the set. What is the easiest way to do it in Java?
views:
63answers:
1
+6
A:
Set<MyObject> mySet = getTheSetFromSomeWhere();
List<MyObject> myObjects = new ArrayList<MyObject>(mySet);
Collections.shuffle(myObjects);
myObjects = myObjects.subList(0, n);
Joachim Sauer
2010-03-24 09:35:41
Cool! I like this solution. I thought it will be something long. But this is short and clear. Thanks!
Roman
2010-03-24 09:39:58
What puzzles me is why there is no `java.util.Arrays.shuffle()` method.
Stephen C
2010-03-24 09:51:40
@Stephen: you can easily work around that missing method by doing `Collections.shuffle(Arrays.asList(myArray))`.
Joachim Sauer
2010-03-24 10:00:25
@Joachim - I was actually thinking the other way around. If there was an Arrays.shuffle, you could do this task with fewer copies.
Stephen C
2010-03-24 10:23:59