Sort HashMap ExampleSort by the keys in a HashMap using the iter and collect functions to convert to a Vector of tuples.
This page was last reviewed on Jul 15, 2023.
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.
Shows a hashmap
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.Shows a hashmap
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 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
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 15, 2023 (edit).
© 2007-2024 Sam Allen.