Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to detect collisions when collecting into a HashMap?

I want to detect and warn about collisions in the logs when collecting a IntoIterator into a HashMap. The current Rust behavior of collecting into a HashMap is to silently overwrite the earlier values with the latest one.

fn main() {
    let a = vec![(0, 1), (0, 2)];
    let b: std::collections::HashMap<_, _> = a.into_iter().collect();
    println!("{}", b[&0]);
}

Output:

2

(Playground)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A possible workaround is collecting into a Vec then manually writing the conversion code, but that will introduce extra allocation overhead and unreadable code. Not consuming the original collection and comparing the len()s is less noisy, but still hogs 1x more memory (?) and can’t detect where exactly the collision is happening.

Is there a more elegent way of handling HashMap collisions?

>Solution :

Depending on what you want to do in the case of a collision, you might be able to use fold (or try_fold) and implement your custom functionality there:

use std::collections::HashMap;

fn main() {
    let a = vec![(0, 1), (0, 3), (0, 2)];

    let b: std::collections::HashMap<_, _> = a.into_iter().fold(HashMap::new(), |mut map, (k,v)| {
        if let Some(&other_value) = map.get(&k) {
            // Pick the higher number
            if v > other_value {
                map.insert(k, v);
            }
        } else {
            map.insert(k, v);
        }
        map
    });

    println!("{}", b[&0]);
}

(Playground)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading