To pull a random item out of a set

Asked 2 years ago, Updated 2 years ago, 105 views

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

2022-09-21 18:29

1 Answers

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.


2022-09-21 18:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.