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 create a new Rust HashMap with values?
- How to use a custom hash function with a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to use a HashBrown with a Rust HashMap?
- How to get the length of a Rust HashMap?
- How to create a HashMap of pointers in Rust?
- How to create a HashMap of traits in Rust?
More of Rust
- How to use non-capturing groups in Rust regex?
- How to escape a Rust regex?
- How to use regex to match a group in Rust?
- How to match the end of a line in a Rust regex?
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to parse a file with Rust regex?
- How to split a string with Rust regex?
- How to use named capture groups in Rust regex?
See more codes...