How to convert a string into a stream of…
Java 11 adds a few new methods to the String class – isBlank, lines, strip, stripLeading, stripTrailing, and repeat. Let’s see how we can make use of the String.lines().
Available from Java 11.
The stream returned by lines() method contains the lines from this string in the same order in which they occur in the multi-line.
/** returns a stream of lines extracted from a given multi-line string line implies that an empty string has zero lines and that there is no empty line following a line terminator at the end of a string **/ public Stream<String> lines()
Example import java.io.IOException; import java.util.stream.Stream; public class Main { public static void main(String[] args) { try { String str = "Line 1\n Line 2\n Line 3\n Line 4"; Stream lines = str.lines(); lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } } Output Line 1 Line 2 Line 3 Line 4