rustHow to sort the keys in a Rust HashMap?
Rust HashMap can be sorted by its keys using the .iter()
method. This method returns an iterator over the key-value pairs in the map, sorted by the keys.
Example code
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
for (key, value) in map.iter() {
println!("{}: {}", key, value);
}
Output example
a: 1
b: 2
c: 3
Code explanation
use std::collections::HashMap;
: imports the HashMap type from the standard library.let mut map = HashMap::new();
: creates a new empty HashMap.map.insert("a", 1);
: inserts a key-value pair into the HashMap.for (key, value) in map.iter() {
: iterates over the key-value pairs in the map, sorted by the keys.println!("{}: {}", key, value);
: prints the key-value pair.
Helpful links
Related
- How to clone a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to use a custom hash function with a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to use an enum in a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
- How to compare two Rust HashMaps?
- How to clear a Rust HashMap?
- How to get a reference to a key in a Rust HashMap?
- How to get all values from a Rust HashMap?
More of Rust
- How to declare a constant HashSet in Rust?
- How to borrow with lifetime in Rust
- How do I get the last character from a string in Rust?
- Bitwise XOR operator usage in Rust
- How do I determine the size of a variable in Rust?
- How to convert struct to protobuf in Rust
- How do I share a variable between structs in Rust?
- How do I convert a string to bytes in Rust?
- rust string doc
- Using Rust box in struct
See more codes...