Hash join: Difference between revisions

→‎{{header|Rust}}: update and genericize
(→‎{{header|Rust}}: update and genericize)
Line 2,505:
=={{header|Rust}}==
<lang rust>use std::collections::HashMap;
use std::hash::Hash;
 
// If you know one of the tables is smaller, it is best to make it the second parameter.
fn hash_join<A, B, K>(first: &[(K, A)], second: &[(K, B)]) -> Vec<(A, K, B)>
where
K: Hash + Eq + Copy,
A: Copy,
B: Copy,
{
let mut hhash_map = HashMap::new();
 
fn main() {
let table_a = vec![
(27, "Jonah"), (18, "Alan"), (28, "Glory"),
(18, "Popeye"), (28, "Alan")
];
let table_b = vec![
("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"),
("Alan", "Zombies"), ("Glory", "Buffy")
];
// hash phase
for &(key, val_a) in second {
let mut h = HashMap::new();
// collect all values by their keys, appending new ones to each existing entry
for (i, a) in table_a.iter().enumerate() {
hhash_map.entry(a.1key).or_insert_with(Vec::new).push(ival_a);
}
 
let mut result = Vec::new();
// join phase
for b&(key, val_b) in table_bfirst {
if let Some(vals) = hhash_map.get(b.0&key) {
forlet &valtuples in= vals.iter().map(|&val_a| (val_b, key, {val_a));
let a = table_aresult.get(val).unwrapextend(tuples);
println!("{:?} {:?}", a, b);
}
}
}
 
result
}
 
</lang>
fn main() {
let table1 = [("Jonah", 27), ("Alan", 18), ("Glory", 28), ("Popeye", 18), ("Alan", 28)];
let table_atable2 = vec![
(27"Jonah", "JonahWhales"), (18"Jonah", "AlanSpiders"), (28"Alan", "GloryGhosts"),
(18"Alan", "PopeyeZombies"), (28"Glory", "AlanBuffy")
];
let result = hash_join(&table1, &table2);
println!("Age | Character Name | Nemesis");
println!("----|----------------|--------");
for (age, name, nemesis) in result {
println!("{:?<3} | {:?^14} | {}", aage, name, bnemesis);
];}
}</lang>
{{out}}
<pre>Age | Character Name | Nemesis
<pre>
----|----------------|--------
(27, "Jonah") ("Jonah", "Whales")
(27, "Jonah") ("| Jonah", "Spiders") | Whales
27 | Jonah | Spiders
(18, "Alan") ("Alan", "Ghosts")
(28,18 | "Alan") ("Alan", " | Ghosts")
(18, "Alan") ("| Alan", " | Zombies")
28 | Glory } | Buffy
(28, "Alan") ("Alan", "Zombies")
28 | Alan | Ghosts
(28, "Glory") ("Glory", "Buffy")
28 | Alan | Zombies</pre>
</pre>
 
=={{header|Scala}}==