Random entry of hashmap

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?

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

1 Like

That worked fine, thanks

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.