views:

63

answers:

1

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?

+6  A: 
Set<MyObject> mySet = getTheSetFromSomeWhere();
List<MyObject> myObjects = new ArrayList<MyObject>(mySet);
Collections.shuffle(myObjects);
myObjects = myObjects.subList(0, n);
Joachim Sauer
Cool! I like this solution. I thought it will be something long. But this is short and clear. Thanks!
Roman
What puzzles me is why there is no `java.util.Arrays.shuffle()` method.
Stephen C
@Stephen: you can easily work around that missing method by doing `Collections.shuffle(Arrays.asList(myArray))`.
Joachim Sauer
@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