Sort map by keys
Rust Programming Language
Problem
Rust program that sorts a map by its keys.
Input
use std::collections::BTreeMap;fn main() {// Create a map with some key-value pairslet mut map = BTreeMap::new();map.insert("foo", 1);map.insert("bar", 2);map.insert("baz", 3);map.insert("qux", 4);// Print out the unsorted mapprintln!("Unsorted map:");for (key, value) in &map {println!("{}: {}", key, value);}// Sort the map by its keyslet sorted_map = map.into_iter().collect::<BTreeMap<_, _>>();// Print out the sorted mapprintln!("Sorted map:");for (key, value) in &sorted_map {println!("{}: {}", key, value);}}{codeBox}
Output
Unsorted map:bar: 2baz: 3foo: 1qux: 4Sorted map:bar: 2baz: 3foo: 1qux: 4{codeBox}
Explanation
In this example, we use a BTreeMap instead of a regular HashMap because BTreeMap is a map implementation that keeps its keys in sorted order. We create a BTreeMap and insert some key-value pairs into it.
Next, we print out the unsorted map by iterating over its key-value pairs using a for loop and the println! macro.
Then, we sort the map by its keys by converting it into an iterator using into_iter, and then collecting the iterator into a new BTreeMap using the collect method. This creates a new BTreeMap with the same key-value pairs as the original map, but with the keys in sorted order.
Finally, we print out the sorted map by iterating over its key-value pairs using a for loop and the println! macro.
The unsorted map first, and then printing out the same map after it has been sorted by its keys. The order of the key-value pairs in the unsorted map is arbitrary, while the key-value pairs in the sorted map are sorted alphabetically by their keys.