Multi-stream: self-join a list to walk a manager chain

A parent id pointing back into the same list is a join of a list with itself. Index it once by id and the chain is a walk - and a null parent is the only thing that terminates it.

Code
record Emp(int id, String name, Integer managerId) {}

var emps = List.of(new Emp(1, "Ava", null), new Emp(2, "Ben", 1), new Emp(3, "Cara", 2));

Map<Integer, Emp> byId = emps.stream().collect(Collectors.toMap(Emp::id, e -> e));

emps.forEach(e -> {
    var chain = new ArrayList<String>();
    Emp cur = e;
    while (cur != null) {
        chain.add(cur.name());
        cur = cur.managerId() == null ? null : byId.get(cur.managerId());
    }
    System.out.println(String.join(" -> ", chain));
});
Output
Ava
Ben -> Ava
Cara -> Ben -> Ava
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