I'd like to iterate through the keys of a HashMap in order. Is there an elegant way to do this? The best I can think of is this:
use std::collections::HashMap;
fn main() {
let mut m = HashMap::<String, String>::new();
m.insert("a".to_string(), "1".to_string());
m.insert("b".to_string(), "2".to_string());
m.insert("c".to_string(), "3".to_string());
m.insert("d".to_string(), "4".to_string());
let mut its = m.iter().collect::<Vec<_>>();
its.sort();
for (k, v) in &its {
println!("{}: {}", k, v);
}
}
I'd like to be able to do something like this:
for (k, v) in m.iter_sorted() {
}
for (k, v) in m.iter_sorted_by(...) {
}
Obviously I can write a trait to do that, but my question is does something like this already exist?
Edit: Also, since people are pointing out that BTreeMap is already sorted I should probably note that while this is true, it isn't actually as fast as a HashMap followed by sort() (as long as you only sort it once of course). Here are some benchmark results for random u32->u32 maps:
Additionally, a BTreeMap only allows a single sort order.

HashMap, this is conceptually the best you can do. If you are fine using aBTreeMap, iteration will automatically be in order.BTreeMap, and I know this is algorithmically optimal. I'm just asking about coding ergonomics - is there a shorter more elegant way to write it basically.