forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream-tolist.yaml
More file actions
44 lines (44 loc) · 1.39 KB
/
stream-tolist.yaml
File metadata and controls
44 lines (44 loc) · 1.39 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
---
id: 40
slug: "stream-tolist"
title: "Stream.toList()"
category: "streams"
difficulty: "beginner"
jdkVersion: "16"
oldLabel: "Java 8"
modernLabel: "Java 16+"
oldApproach: "Collectors.toList()"
modernApproach: ".toList()"
oldCode: |-
List<String> result = stream
.filter(s -> s.length() > 3)
.collect(Collectors.toList());
modernCode: |-
List<String> result = stream
.filter(s -> s.length() > 3)
.toList();
summary: "Terminal toList() replaces the verbose collect(Collectors.toList())."
explanation: "Stream.toList() returns an unmodifiable list. It's equivalent to .collect(Collectors.toUnmodifiableList())\
\ but much shorter. Note: the result is immutable, unlike Collectors.toList()."
whyModernWins:
- icon: "📏"
title: "7 chars vs 24"
desc: ".toList() replaces .collect(Collectors.toList())."
- icon: "🔒"
title: "Immutable"
desc: "The result list cannot be modified."
- icon: "📖"
title: "Fluent"
desc: "Reads naturally at the end of a pipeline."
support:
state: "available"
description: "Widely available since JDK 16 (March 2021)"
prev: "streams/collectors-flatmapping"
next: "streams/stream-mapmulti"
related:
- "collections/unmodifiable-collectors"
- "streams/stream-gatherers"
- "streams/stream-iterate-predicate"
docs:
- title: "Stream.toList()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/stream/Stream.html#toList()"