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();

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.


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

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.