Suppose we have two std::collections::HashMap
-s, say HashMap<K, V1>
and HashMap<K, V2>
, and a function Fn(V1, V2) -> R
.
How do I perform an inner join on these hashmaps so that I get HashMap<K, R>
on their shared keys as a result? Here's a reference implementation to illustrate what I mean:
use std::collections::HashMap;
fn main() {
let mut map_a = HashMap::<&str, i32>::new();
map_a.insert("foo", 1);
map_a.insert("bar", 2);
map_a.insert("qux", 3);
map_a.insert("quux", 4);
let mut map_b = HashMap::<&str, i32>::new();
map_b.insert("foo", 5);
map_b.insert("bar", 6);
map_b.insert("quuux", 7);
map_b.insert("quuuux", 8);
// To keep it simple I'm just combining respective values into a tuple:
let joined_map = map_a
.into_iter()
.filter_map(|(key, value_a)| map_b.remove(key).map(|value_b| (key, (value_a, value_b))))
.collect::<HashMap<&str, (i32, i32)>>();
println!("{:?}", joined_map);
}
An expected output is:
{"foo": (1, 5), "bar": (2, 6)}
This works fine and I can make it generic in a utils.rs
, it just doesn't feel right that I can't find an existing implementation of this in the standard library or on crates.io. Also, it seems suboptimal not to perform kind of sort-merge join, because we already have sorted hash codes underneath HashMap
. Am I overseeing something? Or just being too picky because the lookups are O(1)
anyway?