Elegir un elemento aleatorio de un conjunto

Resuelto Clue Less asked hace 15 años • 34 respuestas

¿Cómo elijo un elemento aleatorio de un conjunto? Estoy particularmente interesado en elegir un elemento aleatorio de un HashSet o LinkedHashSet, en Java.

Clue Less avatar Sep 24 '08 07:09 Clue Less
Aceptado
int size = myHashSet.size();
int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this
int i = 0;
for(Object obj : myhashSet)
{
    if (i == item)
        return obj;
    i++;
}
Khoth avatar Sep 24 '2008 00:09 Khoth

Un ¿Sabías que algo relacionado?

Existen métodos útiles java.util.Collectionspara mezclar colecciones enteras: Collections.shuffle(List<?>)y Collections.shuffle(List<?> list, Random rnd).

chickeninabiscuit avatar Sep 24 '2008 00:09 chickeninabiscuit