flatMap over the same list twice produces every pair; the filter is what makes it a useful set. Remember the size is quadratic - this is the one join shape that turns a small input into a large one.
var hubs = List.of("PNQ", "COK", "DEL");
var legs = hubs.stream()
.flatMap(from -> hubs.stream()
.filter(to -> !from.equals(to))
.map(to -> from + "-" + to))
.toList();
System.out.println(legs.size() + " legs from " + hubs.size() + " hubs");
System.out.println(legs);
6 legs from 3 hubs
[PNQ-COK, PNQ-DEL, COK-PNQ, COK-DEL, DEL-PNQ, DEL-COK]
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