A good answer depends slightly on the circumstances, in particular how often you need to get a random key for a given map (N.B. the technique is essentially the same whether you take key or value).
- If you need various random keys
from a given map, without the map
changing in between getting the
random keys, then use the random
sampling method as you iterate
through the key set. Effectively what
you do is iterate over the set
returned by keySet(), and on each
item calculate the probability of
wanting to take that key, given how
many you will need overall and the
number you've taken so far. Then
generate a random number and see if
that number is lower than the
probability. (N.B. This method will always work, even if you only need 1 key; it's just not necessarily the most efficient way in that case.)
- The keys in a HashMap are effectively
in pseudo-random order already. In an
extreme case where you will only
ever need one random key for a
given possible map, you could even just
pull out the first element of the
keySet().
- In other cases (where you either
need multiple possible random keys
for a given possible map, or the map
will change between you taking random
keys), you essentially have to
create or maintain an array/list of the keys from which you select a
random key.