Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
string
lines
communitycreator

What is the String.lines() method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Java 11 adds a new method called lines to the String class that returns a Stream of lines extracted from a string.

The string is separated for every:

  • Line feed character - \n

  • Carriage return character - \r

  • Carriage return character followed immediately by a line feed character - \r\n

Example

import java.util.stream.Stream;
public class Main
{
public static void main(String[] args)
{
String str = "Line 1 \n Line 2 \r Line 3 \r\n Line 4";
Stream<String> lines = str.lines();
lines.forEach(line -> {
System.out.println(line);
});
}
}

In the above code, we have a string with multiple lines. We separate each line with the String.lines() method, which returns a Stream of lines. We then loop through the stream and print the line.


Points to note:

  • An empty string contains 0 lines.
  • A line can be:
    • zero or more characters followed by a line terminator (e.g., "test\n", "\n").
    • one or more characters followed by end of string (e.g., "test", "a").
  • The stream returned from the lines method is in the same string order as the string where we called the lines method.
  • The line doesn’t include the line terminator.

RELATED TAGS

java
string
lines
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring