-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathstring-lines.yaml
More file actions
46 lines (46 loc) · 1.52 KB
/
string-lines.yaml
File metadata and controls
46 lines (46 loc) · 1.52 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
---
id: 86
slug: "string-lines"
title: "String.lines() for line splitting"
category: "strings"
difficulty: "beginner"
jdkVersion: "11"
oldLabel: "Java 8"
modernLabel: "Java 11+"
oldApproach: "split(\"\\\\n\")"
modernApproach: "lines()"
oldCode: |-
String text = "one\ntwo\nthree";
String[] lines = text.split("\n");
for (String line : lines) {
System.out.println(line);
}
modernCode: |-
String text = "one\ntwo\nthree";
text.lines().forEach(IO::println);
summary: "Use String.lines() to split text into a stream of lines without regex overhead."
explanation: "String.lines() returns a Stream<String> of lines split by \\n, \\r,\
\ or \\r\\n. It is lazier and more efficient than split(), avoids regex compilation,\
\ and integrates naturally with the Stream API for further processing."
whyModernWins:
- icon: "⚡"
title: "Lazy streaming"
desc: "Lines are produced on demand, not all at once like split()."
- icon: "🔧"
title: "Universal line endings"
desc: "Handles \\n, \\r, and \\r\\n automatically without regex."
- icon: "🔗"
title: "Stream integration"
desc: "Returns a Stream for direct use with filter, map, collect."
support:
state: "available"
description: "Available since JDK 11 (September 2018)."
prev: "strings/string-chars-stream"
next: "streams/stream-of-nullable"
related:
- "strings/string-isblank"
- "strings/string-strip"
- "strings/string-indent-transform"
docs:
- title: "String.lines()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html#lines()"