HashMap<&str, u8> to HashMap<u8, &str>

Is there a convenient way of turning std::collections::HashMap<&str, u8> to std::collections::HashMap<u8, &str>, i.e. swapping keys and values, or I need to rebuild it myself? Thanks

It's a one-liner using iterator adaptors:

let new: HashMap<u8, &str> = old.into_iter().map(|(k, v)| (v, k)).collect();
4 Likes

Note that this will pick an arbitrary &str for each collision. If you want to do something else, the code will get a bit more complicated.

2 Likes

Yeah, I meant iterators when said “rebuild it myself". Ok, thanks, I understood there’s no abstraction for this :slight_smile: