Rust Sort HashMap ExampleSort by the keys in a HashMap using the iter and collect functions to convert to a Vector of tuples.
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.
Sorting info. 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.
Example input, output. 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.
Input and output:
x, xyz a, abc SORTED: a, abc x, xyz
Example program. 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.
Step 1 We create a new HashMap (which is like a dictionary) and insert the data into it—the values are not used in this program.
Step 2 We call iter() and collect to get the Vector of tuples from the HashMap. We print the Vector to the screen.
Convert HashMap, vec
Step 3 We invoke sort_by_key to sort each tuple in the Vector by its first item (indexed by the 0 property).
Step 4 Here we use a for-in loop over the result of iter() to loop over the keys and values. We print each key and value to the screen.
String Array
Rust program that sorts HashMap by keys
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
A review. 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.
© 2007-2022 sam allen.
see site info on the changelog.