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.
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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 15, 2023 (edit).