Java 11 String lines function example to split it in lines

In Java 11 String class introduces lines function to split it into lines with new line separator.

Java 11 String lines function example to split it in lines

In Java 11 String class introduces lines function to split it into lines with new line separator.

Java 11 String lines function example to split it in lines

Java 11 String lines function - How to split String into lines in Java 11?

In this tutorial we are going to explain use the use of new function which is introduced in Java 11 which is used to split lines in Java. Java 11 introduced many new features and improvements to make programming language much useful. In this version of Java (JDK 11) String class introduces a new method String.lines() which splits the string object into lines. The line separator used is \n or \r\n.

If your String object contains these new line characters then you can easily and efficiently use the lines() method the string into lines. This method is described in the bug report JDK-8200425, which provides more details about this method. This method is approved and available in current build of JDK 11.

In JDK 11 the java.lang.String class comes with a  new method lines(), which returns a stream of the lines from the string object. This method is very useful in processing multi-line string in their program. This method makes life easy as in real world programming it is required to process multi-line string very frequently.

Today I am trying lines() method of Java 11 to split multi-line string. Here is the full example code:

import java.util.stream.Stream;

public class StringLinesExample 
{
	public static void main(String[] args) 
	{
		//New line seperator \n
		String s = "Line 1\nLine2\nLine 3\nLine4";
		Stream<String> lines = s.lines();
		lines.forEach(System.out::println);
        lines.close();
		
		//New Line Seperator \r\n
		s = "Line 1\r\nLine2\r\nLine 3\r\nLine4";
		lines = s.lines();
		lines.forEach(System.out::println);
        lines.close();
	}
}

In the above example we have used the lines() method which returns Stream of lines:

Stream<String> lines = s.lines();

If you run  the example it will print all lines in the String object.

Here is the output of the program:

C:\java11examples>java StringLinesExample
Line 1
Line2
Line 3
Line4
Line 1
Line2
Line 3
Line4

In this tutorial we have learned to use the lines() method which is introduced in Java 11.

Check more tutorials at: