How do I pull out random items in Set? I want to pick random elements from HashSet or LinkedSet, but I don't know how.
algorithm random java language-agnostic
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 = i + 1;
}
Here's how it works.
© 2024 OneMinuteCode. All rights reserved.