Learn to convert multi-line string into stream of lines using String.lines() method in Java 11.
This method is useful when we want to read content from a file and process each string separately.
1. String.lines() API
The lines() method is a static method. It returns a stream of lines extracted from a given multi-line string, separated by line terminators. 
/** * returns - the stream of lines extracted from given string */ public Stream<String> lines()
A line terminator is one of the following –
- a line feed character (“\n”)
- a carriage return character (“\r”)
- a carriage return followed immediately by a line feed (“\r\n”)
By definition, a line is zero or more character followed by a line terminator. A line does not include the line terminator.
The stream returned by lines() method contains the lines from this string in the same order in which they occur in the multi-line.
2. Java program to get stream of lines
Java program to read a file and get the content as stream of lines.
import java.io.IOException;
import java.util.stream.Stream;
public class Main 
{
	public static void main(String[] args) 
	{
		try 
		{
			String str = "A \n B \n C \n D"; 
			Stream<String> lines = str.lines();
			lines.forEach(System.out::println);
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}
Program output.
A B C D
Drop me your questions related to reading a string into lines of stream.
Happy Learning !!
 
					 
Comments