Back
How do I pick a random element from a set? I'm particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java. Solutions for other languages are also welcome.
Try:
int size = myHashSet.size();int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than thisint i = 0;for(Object obj : myhashSet){ if (i == item) return obj; i++;}
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++;
}
31k questions
32.8k answers
501 comments
693 users