armanriazi rust collection hashmap avoid_of_duplicate
To avoid duplicates in a Rust HashMap
, you can use the entry
API along with the or_insert
method. Here's an example:
use std::collections::HashMap;
fn main() {
let mut hashmap: HashMap<i32, String> = HashMap::new();
hashmap.entry(1).or_insert("value1".to_string());
hashmap.entry(2).or_insert("value2".to_string());
hashmap.entry(1).or_insert("value3".to_string());
for (key, value) in hashmap {
println!("Key: {}, Value: {}", key, value);
}
}
In this example, we create a HashMap
called hashmap
that maps i32
keys to String
values. We use the entry
method to access the entry for a specific key. The entry
method returns an Entry
enum, which represents the key-value pair in the map. We then use the or_insert
method to insert a value if the key does not exist in the map. If the key already exists, the or_insert
method will return a mutable reference to the existing value.
In the example, we insert three key-value pairs into the hashmap
. The first two entries have unique keys, so they are inserted into the map. However, the third entry has a key that already exists, so it is not inserted again. Instead, the existing value associated with the key is returned.
Finally, we iterate over the hashmap
and print each key-value pair. The output will be:
Key: 1, Value: value1
Key: 2, Value: value2
This demonstrates how to use the entry
API to avoid duplicates in a HashMap
in Rust.