A left join must not silently drop rows whose key is missing on the right. Optional.ofNullable around the lookup turns a null into a visible default instead of a NullPointerException three lines later.
record Product(String sku, String name) {}
record Line(String sku, int qty) {}
var products = List.of(new Product("S1", "Pen"), new Product("S2", "Book"));
var lines = List.of(new Line("S1", 2), new Line("S9", 5), new Line("S2", 1));
Map<String, Product> bySku = products.stream()
.collect(Collectors.toMap(Product::sku, p -> p));
lines.stream()
.map(l -> l.sku() + " x" + l.qty() + " -> "
+ Optional.ofNullable(bySku.get(l.sku()))
.map(Product::name)
.orElse("<unknown sku>"))
.forEach(System.out::println);
S1 x2 -> Pen
S9 x5 -> <unknown sku>
S2 x1 -> Book
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