rustHow to sort a Rust HashMap?
A Rust HashMap can be sorted using the sort_by method. This method takes a closure as an argument which is used to compare two elements of the HashMap. The closure should return Ordering::Less if the first element is less than the second, Ordering::Equal if they are equal, and Ordering::Greater if the first element is greater than the second.
Example code
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let mut sorted_map = map.into_iter().collect::<Vec<_>>();
sorted_map.sort_by(|a, b| a.1.cmp(&b.1));
Output example
[("a", 1), ("b", 2), ("c", 3)]
Code explanation
let mut map = HashMap::new();: This creates a new empty HashMap.map.insert("a", 1);: This inserts a key-value pair into the HashMap.let mut sorted_map = map.into_iter().collect::<Vec<_>>();: This converts the HashMap into a vector of tuples.sorted_map.sort_by(|a, b| a.1.cmp(&b.1));: This sorts the vector of tuples using thesort_bymethod. The closure passed to the method compares the second element of each tuple (a.1andb.1) and returnsOrdering::Less,Ordering::Equal, orOrdering::Greaterdepending on the comparison result.
Helpful links
Related
- How to print a Rust HashMap?
- How to create a HashMap of structs in Rust?
- How to create a HashMap of pointers in Rust?
- How to clear a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to use a tuple as a key in a Rust HashMap?
- How to compare two Rust HashMaps?
- How to check if a Rust HashMap contains a key?
- How to add a value to a Rust HashMap?
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to convert a u8 slice to a hex string in Rust?
- How to split a string with Rust regex?
- How to use regex lookbehind in Rust?
- How to parse a file with Rust regex?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
See more codes...