Reading:
Java Split Lines to Hashmap

Java Split Lines to Hashmap

Metamug

//: # ()

Split multiline string into lines

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.

Using streams to split string

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.



Icon For Arrow-up
Comments

Post a comment