Multi-stream: flatten nested lists and re-key by the parent

flatMap loses the parent unless you carry it along in the pair you emit. Note the empty child list simply contributes nothing - which is why the parent with no children has to be found separately.

Code
record Batch(String id, List<String> serials) {}

var batches = List.of(new Batch("B1", List.of("s1", "s2")),
                      new Batch("B2", List.of("s3")),
                      new Batch("B3", List.of()));

Map<String, String> batchOf = batches.stream()
        .flatMap(b -> b.serials().stream().map(s -> Map.entry(s, b.id())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, TreeMap::new));

System.out.println(batchOf);
System.out.println("empty batches: "
        + batches.stream().filter(b -> b.serials().isEmpty()).map(Batch::id).toList());
Output
{s1=B1, s2=B1, s3=B2}
empty batches: [B3]
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