Ordered hashmap?

When we iterate over HashMap<usize, T> it's not always ordered. Same for BTreeMap. Are there ways for doing the iteration in order like 0,1,2,3, etc for the keys?

Found a good answer on SO:

A BTreeMap is always ordered by keys. There is no ordering for a HashMap.


You could use IndexMap: it's a HashMap that maintains insertion order, but you can also call sort_keys as needed. I would try to batch that though, as it's a fairly heavy operation.


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.