Learnitweb

String lines() method in Java

1. Introduction

The signature of the lines() method introduced in Java 11 is:

public Stream<String> lines()

This method returns a stream of lines extracted from the string, separated by line terminators. This method returns a stream which contains the lines from this string in the same order in which they occur in the string.

A line terminator is one of the following:

  • a line feed character “\n” (U+000A)
  • a carriage return character “\r” (U+000D)
  • carriage return followed immediately by a line feed “\r\n” (U+000D U+000A)

A line is either a sequence of zero or more characters followed by a line terminator, or it is a sequence of one or more characters followed by the end of the string. A line does not include the line terminator. This definition of line implies:

  • An empty string has no lines.
  • There is no empty line following a line terminator at the end of string.

2. Benefits

  • Before Java 11, the common way of getting lines from a Java String was to split (“\R”). The lines() method provides a simple and cleaner way to achieve the same result.
  • The lines() method is lazy in comparison of split method. This has better performance and faster in searching new line terminators.

3. Example

Now let us see an example of lines() method.

public class LinesMethodExample {
    public static void main(String args[]) {
        String str = "hello\nworld\nfrom\nme";
        Stream<String> lines = str.lines();
        lines.forEach(System.out::println);
    }
}

Output

hello
world
from
me

4. Conclusion

In conclusion, the lines() method in Java provides a convenient way to read lines from a text file as a stream of strings. It’s a powerful tool for processing large files efficiently and simplifying the handling of line-based data. By utilizing this method along with other stream operations and functionalities available in Java, developers can create robust and scalable applications for various use cases involving file processing. Understanding how to use lines() effectively can significantly enhance your productivity and the performance of your Java applications when dealing with text files.