Multi-stream: cross join with flatMap, filtered down to valid pairs

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.

Code
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);
Output
6 legs from 3 hubs
[PNQ-COK, PNQ-DEL, COK-PNQ, COK-DEL, DEL-PNQ, DEL-COK]
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