Java: a hash join and why it beats a nested loop

A database join pairs rows from two tables whose key columns match. The simplest method, the nested-loop join, compares every row of one table with every row of the other. A hash join builds a hash table of the smaller table's keys once and then looks each row of the other table up in it.

Java
import java.util.*;

class Main {
  static class Employee {
    final String name;
    final int deptId;

    Employee(String name, int deptId) {
      this.name = name;
      this.deptId = deptId;
    }
  }

  public static void main(String[] args) {
    Map<Integer, String> departments = new HashMap<>();
    departments.put(1, "Eng");
    departments.put(2, "Ops");

    List<Employee> staff = List.of(
        new Employee("Ada", 1), new Employee("Bo", 2),
        new Employee("Cy", 1), new Employee("Di", 3));

    int probes = 0;
    for (Employee e : staff) {
      probes++;
      String title = departments.get(e.deptId);
      if (title != null) {
        System.out.println(e.name + " -> " + title);
      }
    }
    System.out.println("probes=" + probes + " nested-loop comparisons=" + staff.size() * departments.size());
  }
}
Read the full lesson