forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream-mapmulti.json
More file actions
50 lines (50 loc) · 1.82 KB
/
Copy pathstream-mapmulti.json
File metadata and controls
50 lines (50 loc) · 1.82 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
{
"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 ->\n order.items().stream()\n .map(item -> new OrderItem(\n order.id(), item)\n )\n);",
"modernCode": "stream.<OrderItem>mapMulti(\n (order, downstream) -> {\n for (var item : order.items())\n downstream.accept(\n new OrderItem(order.id(), item));\n }\n);",
"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)"
}
]
}