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?

Was it helpful?

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
scroll top