javarandomsetkeyset

How to pull random string from a keySet?


I'm working on a problem in which I need to pull a random String from a keySet. Just wondering if anyone can give me some direction here. I'm pretty lost on it. I've found quite a few ways to do it if I were using an int, but not a String. For example I want to quiz a user on States and their Capitals, and to pull out a random Key from the keySet for the question. Here's the set:

Set<String> states = stateCapitals.keySet();

Solution

  • Set is not the best data structure for random indexing.

    Better convert to a List and use a random generator to select an index. If you really need to stay with a Set, you can generate a random index n and iterate through the Set, stop at the nth element. For selecting multiple elements, there is no benefit of working with a List. Any iterable would be fine.

    The key idea is to dynamically adjust selection probability so you can choose m (out of sizeof(Set)): In the easiest example of m=1, select 1st element with probability of 1/N, if you didn't select it, select 2nd element with probability 1/(N-1)..and so on.

    Use conditional probability to show all elements are selected under a fair chance 1/N.