How to extract N random different elements from a set of unique elements?
Question
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?
Solution
Set<MyObject> mySet = getTheSetFromSomeWhere();
List<MyObject> myObjects = new ArrayList<MyObject>(mySet);
Collections.shuffle(myObjects);
myObjects = myObjects.subList(0, n);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow