Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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.

1 Answer

0 votes
by (46k points)

Try:

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++;

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...