In this guide, you will learn about the String lines() method in Java programming and how to use it with an example.
1. String lines() Method Overview
Definition:
The lines() method is a part of the String class in Java, introduced in Java 11. This method is used to return a stream of lines extracted from the original string, separated by line terminators (\n, \r, or \r\n).
Syntax:
public Stream<String> lines()
Parameters:
This method does not take any parameters.
Key Points:
- The method returns a Stream of substrings, each representing a line of the original string.
- A line terminator is a one-character or two-character sequence that marks the end of a line of the input character sequence.
- If the string ends in a line terminator, the final element of the stream is an empty string following the last line terminator.
- If the string does not have any line terminators, it returns a single-line stream.
2. String lines() Method Example
public class LinesExample {
public static void main(String[] args) {
String str = "Java\r\nis\nFun";
str.lines().forEach(System.out::println);
}
}
Output:
Java is Fun
Explanation:
In this example, a multi-line string str is defined with different line terminators: \r\n and \n. When the lines() method is called on this string, it returns a Stream of three substrings, each representing a line of the original string. The forEach method is then used to print each line to the console.
Comments
Post a Comment
Leave Comment