-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathstream-mapmulti.yaml
More file actions
52 lines (52 loc) · 1.59 KB
/
stream-mapmulti.yaml
File metadata and controls
52 lines (52 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
---
id: 41
slug: "stream-mapmulti"
title: "Stream.mapMulti()"
category: "streams"
difficulty: "intermediate"
jdkVersion: "16"
oldLabel: "Java 8"
modernLabel: "Java 16+"
oldApproach: "flatMap + List"
modernApproach: "mapMulti()"
oldCode: |-
stream.flatMap(order ->
order.items().stream()
.map(item -> new OrderItem(
order.id(), item)
)
);
modernCode: |-
stream.<OrderItem>mapMulti(
(order, downstream) -> {
for (var item : order.items())
downstream.accept(
new OrderItem(order.id(), item));
}
);
summary: "Emit zero or more elements per input without creating intermediate streams."
explanation: "mapMulti() is an imperative alternative to flatMap that avoids creating\
\ intermediate Stream objects for each element. It's more efficient when the mapping\
\ produces a small number of elements."
whyModernWins:
- icon: "⚡"
title: "Less allocation"
desc: "No intermediate Stream created per element."
- icon: "🎯"
title: "Imperative style"
desc: "Use loops and conditionals directly."
- icon: "📐"
title: "Flexible"
desc: "Emit zero, one, or many elements with full control."
support:
state: "available"
description: "Widely available since JDK 16 (March 2021)"
prev: "streams/stream-tolist"
next: "streams/stream-gatherers"
related:
- "streams/stream-iterate-predicate"
- "streams/stream-of-nullable"
- "streams/stream-gatherers"
docs:
- title: "Stream.mapMulti()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/stream/Stream.html#mapMulti(java.util.function.BiConsumer)"