Hash join: Difference between revisions

Content added Content deleted
(→‎{{header|Java}}: added Java)
Line 840: Line 840:
│Glory│28│Buffy │
│Glory│28│Buffy │
└─────┴──┴───────┘</lang>
└─────┴──┴───────┘</lang>

=={{header|Java}}==
{{trans|PHP}}
{{works with|Java|8}}
<lang java>import java.util.*;

public class HashJoin {

public static void main(String[] args) {
String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
{"18", "Popeye"}, {"28", "Alan"}};

String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
{"Bob", "foo"}};

hashJoin(table1, 1, table2, 0).stream()
.forEach(r -> System.out.println(Arrays.deepToString(r)));
}

static List<String[][]> hashJoin(String[][] records1, int idx1,
String[][] records2, int idx2) {

List<String[][]> result = new ArrayList<>();
Map<String, List<String[]>> map = new HashMap<>();

for (String[] record : records1) {
List<String[]> value = map.get(record[idx1]);
if (value == null)
value = new ArrayList<>();
value.add(record);
map.put(record[idx1], value);
}

for (String[] record : records2) {
List<String[]> lst = map.get(record[idx2]);
if (lst != null) {
lst.stream().forEach(r -> {
result.add(new String[][]{r, record});
});
}
}

return result;
}
}</lang>

<pre>[[27, Jonah], [Jonah, Whales]]
[[27, Jonah], [Jonah, Spiders]]
[[18, Alan], [Alan, Ghosts]]
[[28, Alan], [Alan, Ghosts]]
[[18, Alan], [Alan, Zombies]]
[[28, Alan], [Alan, Zombies]]
[[28, Glory], [Glory, Buffy]]</pre>


=={{header|jq}}==
=={{header|jq}}==