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 build a Rust HashMap from an iterator?
- How to use a Rust HashMap in a struct?
- How to use an enum in a Rust HashMap?
- How to convert a Rust HashMap to a BTreeMap?
- How to convert a Rust HashMap to a JSON string?
- How to implement PartialEq for a Rust HashMap?
- How to compare two Rust HashMaps?
- How to clone a Rust HashMap?
- How to pop an element from a Rust HashMap?
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- How to match the end of a line in a Rust regex?
- How to convert JSON to a struct in Rust?
- How to escape dots with regex in Rust?
- How to replace a capture group using Rust regex?
- How to declare a matrix in Rust?
- How to match a string with regex in Rust?
- How to calculate the inverse of a matrix in Rust?
See more codes...