Can I iterate in order on `HashMap<usize, MyStruct>`?

If I have:

my_hash_map: HashMap<usize, MyStruct>,

and I do:


I get a HashMapIter<'_, usize, MyStruct> that iterates in arbitrary order.

Is there a way to iterate in the order of the keys? They are ordered because the key is a usize

Change your type to BTreeMap<usize, MyStruct> which stores the keys in order. HashMap doesn't store keys in order.


Another option is to collect the keys into a vector and sort it.

1 Like