Split multiline string and add each line into a map using streams
//: # ()
Java 11 provides String.lines()
method to split the string into lines. Traditionally, developers needed to split the lines using line separator regex.
Stream<String> stream = string.lines();
The lines()
method returns a Stream
of lines.
Here we have split the line using the equals operator and used collect function to create the hashmap
stream.map(line-> line.split("=")).collect(Collectors.toMap(a->a[0],a->a[1]));
Example:
name=John Doe
age=32
place=New York
This above string will be split into lines and collected into a hashmap of size 3 with their respective key/value pair.