How to push HashMap values into Vec in order?


#1
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.


#2

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.


#3

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).


#4

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


#5

Thank you, I’ll try it.