Random entry of hashmap

#1

I have a HashMap<K,V> and I want to get a random entry from that map.

Currently I have map.keys().next(), but it turns out this is not at all random enough for my algorithm. I could collect all keys in a Vec and then randomly choose an index. However, this requires traversing the whole map.

Is there any quicker way to get a reasonable random entry from the map?

0 Likes

#2

https://crates.io/crates/indexmap has a hashmap with efficient indexing that you could use for this.

1 Like

#3

That worked fine, thanks

0 Likes