Sort
HashMap
Programs use HashMaps
to store look up data—keys matched to values. This optimizes performance, but it eliminates the ability to sort and order items.
By converting the HashMap
and its tuple data to a Vector
, we can sort the data by the keys or values. This creates a copy of the collection, but is needed for sorting.
Consider these requirements: we have a HashMap
that has 2 keys—the 1-character strings "x" and "a." We want to loop over them in alphabetical order.
x, xyz a, abc SORTED: a, abc x, xyz
Here we implement the conversion method and invoke sort_by_key
in Rust code. Please notice that we have a "use" statement at the top.
HashMap
(which is like a dictionary) and insert the data into it—the values are not used in this program.iter()
and collect to get the Vector
of tuples from the HashMap
. We print the Vector
to the screen.sort_by_key
to sort each tuple in the Vector
by its first item (indexed by the 0 property).for-in
loop over the result of iter()
to loop over the keys and values. We print each key and value to the screen.use std::collections::HashMap; fn main() { // Step 1: create HashMap. let mut source = HashMap::new(); source.insert("x", "xyz"); source.insert("a", "abc"); // Step 2: get Vector from HashMap. let mut sorted: Vec<_> = source.iter().collect(); println!("{:?}", sorted); // Step 3: sort Vector by key from HashMap. // ... This sorts by HashMap keys. // Each tuple is sorted by its first item. sorted.sort_by_key(|a| a.0); println!("{:?}", sorted); // Step 4: loop over sorted vector. for (key, value) in sorted.iter() { println!("KEY, VALUE: {} {}", key, value); } }[("a", "abc"), ("x", "xyz")] [("a", "abc"), ("x", "xyz")] KEY, VALUE: a abc KEY, VALUE: x xyz
With this code we can sort the keys (or values of a HashMap
) using the sort_by_key
function. We must specify 0 or 1 for the key or value.