Java 11 - String lines() method example

Java 11 added a few useful APIs to the commonly used String class.  The string lines() method is one of them. In this post, we will see the usage of String lines() method with an example.

String lines() API - Java 11

The lines() String class method returns a Stream of lines extracted from the string, separated by line terminators:
package net.javaguides.examples;

import java.util.stream.Stream;

/**
 * Java 11 (JDK11) New String APIs/Methods with Examples
 * 
 * @author Ramesh Fadatare
 *
 */
public class StringAPIInJDK11 {
    public static void main(String[] args) {
        /**
         * The lines() instance method returns a Stream of lines extracted from the
         * string, separated by line terminators
         */
        String multilineStr = "This is\n a multiline\n string.";

        Stream < String > stream = multilineStr.lines();
        stream.forEach(action - > System.out.println(action));

        long lineCount = multilineStr.lines().count();
        System.out.println(lineCount);
    }
}
Output:
This is
 a multiline
 string.
3
A line terminator is one of the following: “\n”, “\r”, or “\r\n”.
The stream contains lines in the order in which they occur. The line terminator is removed from each line.

Reference



Comments