How to push HashMap values into Vec in order?

use std::collections::HashMap;
fn main() {
  let mut hash = HashMap::new();
  hash.insert("x1", 1);
  hash.insert("x2", 2);
  hash.insert("x3", 3);
  hash.insert("x4", 4);
  
  let mut v = Vec::new();
  for (_, val) in hash.iter_mut() {
    v.push(*val * *val);
  } 
  
  println!("v: {:?}", v);
}

Rust Playground

I want a vec: [1, 4, 9, 16], but it prints out randomly like [4, 1, 16, 9] / [16, 9, 1, 4] etc, everytime I execute it.

1 Like

Hash map is an unordered collection, so the order of insert calls doesn't matter for it. Its main purpose is to allow fast lookup by key. If you want to preserve order, you can use a vector, e.g. Vec<(String, i32)> to store both keys and values, but fast lookup by key won't be available.

2 Likes

If you use a BTreeMap instead of a HashMap, then you will be able to iterate through the elements in order (besides being able to perform relatively fast lookup by key).

2 Likes

You might like ordermap for a hash map that maintains insertion order.

3 Likes

Thank you, I'll try it.