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_by
method. The closure passed to the method compares the second element of each tuple (a.1
andb.1
) and returnsOrdering::Less
,Ordering::Equal
, orOrdering::Greater
depending on the comparison result.
Helpful links
Related
- How to implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to convert a Rust HashMap to JSON?
- How to convert the keys of a Rust HashMap to a vector?
- How to convert a Rust HashMap to a JSON string?
- How to use a HashBrown with a Rust HashMap?
- How to sort the keys in a Rust HashMap?
- How to use a custom hash function with a Rust HashMap?
- How to remove an element from a Rust HashMap if a condition is met?
- How to create a Rust HashMap with a string key?
More of Rust
- How to use regex to match a double quote in Rust?
- How to use regex to match a group in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to convert a Rust HashMap to a BTreeMap?
- How to get a capture group using Rust regex?
- How to parse JSON string in Rust?
- How to use a tuple as a key in a Rust HashMap?
- How to convert a Rust slice to a fixed array?
- How to split a string by regex in Rust?
- How to convert a Rust HashMap to a JSON string?
See more codes...