Multi-stream: inner join with flatMap and Optional.stream()

Optional.stream() yields zero or one element, so flatMapping it over a lookup drops every unmatched row. That is exactly an inner join - and it needs no filter/get pair that a reader has to check for safety.

Code
record Dept(int id, String name) {}
record Emp(String name, int deptId) {}

var depts = List.of(new Dept(10, "Core"), new Dept(20, "Data"));
var emps = List.of(new Emp("Ava", 10), new Emp("Ben", 99), new Emp("Cara", 20));

Map<Integer, Dept> byId = depts.stream().collect(Collectors.toMap(Dept::id, d -> d));

var joined = emps.stream()
        .flatMap(e -> Optional.ofNullable(byId.get(e.deptId()))
                              .map(d -> e.name() + "@" + d.name())
                              .stream())
        .toList();

System.out.println(joined);
System.out.println("dropped: " + (emps.size() - joined.size()));
Output
[Ava@Core, Cara@Data]
dropped: 1
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-20

© Java Coding Hub · About · Contact · Privacy · Terms