MapMulti One To Many Without Streams
Flatten each element to zero or more outputs with Stream mapMulti, avoiding the per-element stream allocation that flatMap pays for.
Code
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class TagIndex {
public static void main(String[] args) {
// LinkedHashMap:迭代顺序固定,输出可复现
Map<String, List<String>> docs = new LinkedHashMap<>();
docs.put("order-api", List.of("rest", "json"));
docs.put("batch-job", List.of("cron", "rest"));
docs.put("readme", List.of());
// mapMulti:一个元素产出 0..n 个结果,下游 accept 即收集
// readme 没有任何标签 → 零产出,天然被跳过
List<String> pairs = docs.entrySet().stream()
.<String>mapMulti((entry, downstream) -> {
for (String tag : entry.getValue()) {
downstream.accept(entry.getKey() + ":" + tag);
}
})
.toList();
System.out.println(pairs);
// 同一结果的 flatMap 写法:每个元素都要先包一层 Stream
List<String> viaFlatMap = docs.entrySet().stream()
.flatMap(entry -> entry.getValue().stream()
.map(tag -> entry.getKey() + ":" + tag))
.toList();
System.out.println("same result: " + pairs.equals(viaFlatMap));
}
}The mapMulti shape
mapMulti hands each element a downstream consumer; the lambda calls downstream.accept(…) once per produced value. The TagIndex demo maps every doc entry to doc:tag strings, and the readme entry with an empty tag list simply produces nothing — no wrapper object per element.
Against flatMap
The same result via flatMap is shown for comparison: each entry must first become a Stream (entry.getValue().stream().map(…)) before flattening. The demo prints same result: true, confirming equality, while mapMulti skips those per-element stream allocations.
Deterministic order
docs is a LinkedHashMap, so the pair list prints in insertion order — order-api:rest, order-api:json, batch-job:cron, batch-job:rest.
Interactive Tools for This Topic
FAQ
- When is mapMulti preferable to flatMap?
- When each element yields few (often zero) results; mapMulti avoids allocating a stream per element the way flatMap does.
- How does the empty readme entry behave?
- Its tag list is empty, so downstream.accept never runs and the entry contributes nothing to the pair list — no special-casing needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.