Pregunta

I tiene un conjunto de elementos únicos (no hay dos elementos idénticos). Y me gustaría extraer N azar y diferentes elementos del conjunto. ¿Cuál es la forma más fácil de hacerlo en Java?

¿Fue útil?

Solución

Set<MyObject> mySet = getTheSetFromSomeWhere();
List<MyObject> myObjects = new ArrayList<MyObject>(mySet);
Collections.shuffle(myObjects);
myObjects = myObjects.subList(0, n);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top