Java String lines method

Let’s see the String lines method in Java. After Java 11 there is a new method String.lines(), which is useful if you have a multi-line string and you need to process each line.

Definition of the method:

public Stream<String> lines()

Example on how to use it:

public class MainStringExample {
    public static void main(String[] args) {
        String stringOnTwoLines = "This is string\n on two lines";
        System.out.println(stringOnTwoLines);

        // add space between outputs
        System.out.println();

        // After Java 11 you can use lines method on string
        // which is giving you stream of string lines
        stringOnTwoLines.lines()
                .map(l -> "Line Start >> " + l + " << Line end ")
                .forEach(System.out::println);
    }
}
This is string
 on two lines

Line Start >> This is string << Line end 
Line Start >>  on two lines << Line end 

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.