Introduction
The String.lines()
method, introduced in Java 11, provides an easy way to split a string into a stream of lines. Each line is separated based on line terminators such as \n
(newline) or \r\n
(carriage return followed by newline). This method is particularly useful for reading multi-line strings and processing each line independently.
The lines()
method returns a Stream<String>
, which can be further processed using the powerful Stream API operations like filtering, mapping, or collecting.
Solution Steps
- Create a Multi-Line String: Start by creating a string that contains multiple lines.
- Use
lines()
Method: Call thelines()
method on the string to get a stream of lines. - Process the Stream: You can iterate through the lines or perform operations like filtering, collecting, or printing.
- Display the Output: Print each line or process it based on the required logic.
Java Program
Example 1: Basic Usage of lines()
public class StringLinesExample {
public static void main(String[] args) {
// Step 1: Create a multi-line string
String text = "Java is fun.\nJava is powerful.\nJava 11 introduced new features.";
// Step 2: Use the lines() method to get a stream of lines
text.lines().forEach(System.out::println);
}
}
Output
Java is fun.
Java is powerful.
Java 11 introduced new features.
Explanation
- Step 1: Create a Multi-Line String
A stringtext
is created with three lines, separated by newline characters (\n
):
String text = "Java is fun.\nJava is powerful.\nJava 11 introduced new features.";
- Step 2: Use
lines()
Method
Thelines()
method splits the string into individual lines, each one separated by newline characters. The result is aStream<String>
:
text.lines().forEach(System.out::println);
Here, we use the forEach()
method to print each line in the stream.
Example 2: Using lines()
with Stream Operations
import java.util.List;
import java.util.stream.Collectors;
public class StringLinesStreamExample {
public static void main(String[] args) {
// Step 1: Create a multi-line string
String text = "Java is fun.\nJava is powerful.\nJava is evolving.\n";
// Step 2: Use lines() to get a stream and filter out lines containing "fun"
List<String> filteredLines = text.lines()
.filter(line -> line.contains("fun"))
.collect(Collectors.toList());
// Step 3: Display the filtered lines
filteredLines.forEach(System.out::println);
}
}
Output
Java is fun.
Explanation
Step 1: Create a Multi-Line String
A stringtext
is created, and it contains multiple lines, similar to the previous example.Step 2: Filter the Stream of Lines
Thelines()
method splits the string into individual lines and returns aStream<String>
. The stream is then filtered using thefilter()
method to only retain lines that contain the word "fun":
List<String> filteredLines = text.lines()
.filter(line -> line.contains("fun"))
.collect(Collectors.toList());
- Step 3: Display the Filtered Lines
Finally, the filtered lines are collected into a list and printed usingforEach()
:
filteredLines.forEach(System.out::println);
Example 3: Counting the Number of Lines in a String
public class StringLinesCountExample {
public static void main(String[] args) {
// Step 1: Create a multi-line string
String text = "First line\nSecond line\nThird line";
// Step 2: Count the number of lines in the string
long lineCount = text.lines().count();
// Step 3: Display the count
System.out.println("Number of lines: " + lineCount);
}
}
Output
Number of lines: 3
Explanation
- Step 1: Create a Multi-Line String
We create a multi-line stringtext
containing three lines:
String text = "First line\nSecond line\nThird line";
- Step 2: Count the Number of Lines
Thelines()
method is used to get a stream of lines, and thecount()
method counts the number of lines:
long lineCount = text.lines().count();
- Step 3: Display the Count
Finally, the program prints the number of lines in the string.
Example 4: Collecting Lines into a List
import java.util.List;
public class StringLinesToListExample {
public static void main(String[] args) {
// Step 1: Create a multi-line string
String text = "Apple\nBanana\nCherry";
// Step 2: Collect the lines into a List
List<String> fruits = text.lines().collect(Collectors.toList());
// Step 3: Display the List
System.out.println(fruits);
}
}
Output
[Apple, Banana, Cherry]
Explanation
- Step 1: Create a Multi-Line String
We create a multi-line string with the names of fruits:
String text = "Apple\nBanana\nCherry";
- Step 2: Collect Lines into a List
Thelines()
method is used to split the string into lines, and thecollect()
method collects the stream of lines into aList<String>
:
List<String> fruits = text.lines().collect(Collectors.toList());
- Step 3: Display the List
Finally, we print the list of lines (fruits):
System.out.println(fruits);
Key Points
- Line Terminators: The
lines()
method splits the string based on line terminators like\n
(newline),\r\n
(carriage return followed by newline), or\r
(carriage return). - Stream API: The
lines()
method returns aStream<String>
, making it compatible with Stream API operations likefilter()
,map()
,collect()
, and more. - Empty Lines: If there are consecutive line terminators, the
lines()
method will treat that as an empty line. - Use Cases: You can use
lines()
to read and process multiline strings, count lines, filter lines based on conditions, and collect lines into collections like lists.
Conclusion
The lines()
method in Java 11 provides a convenient way to split strings into individual lines and process them using the Stream API. Whether you're filtering lines, counting lines, or transforming the data, the lines()
method simplifies text processing, making your code cleaner and more efficient. It also integrates seamlessly with other Stream API operations, giving you flexibility when handling multi-line strings.
Comments
Post a Comment
Leave Comment