Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap using streams and substring

I am wondering how to achieve the following.

"t12345-g1234-o1234"

I have a line that contains multiple fields delimited by an hyphen and the field is formed by its identifier(first letter) and value.

How can I achieve an Map like the one below using java 8 streams.

{"t","12345"} , {"g","1234"}, {"o","1234"}

EDIT

I have tried the following, but I don't understand how to grab the substring information.

Arrays.stream(line.split("-"))
.collect(Collectors.toMap(String::substring(0,1),String::substring(1));
like image 509
Ricardo Joenck Avatar asked Sep 02 '18 12:09

Ricardo Joenck


1 Answers

You can use Collectors.toMap

Map<String, String> result = Arrays.stream(s.split("-"))
            .collect(Collectors.toMap(part -> part.substring(0, 1),
                    part -> part.substring(1)));

The first argument to toMap is the keyMapper. It picks the key as the first character in the split string part. part.substring(0, 1) - It will return the substring starting at index 0 of length 1 (which is the first character).

The second argument is the valueMapper. It is the rest that follows the first character. part.substring(1) - Returns the substring starting at index 1 (since no end index is specified, it will be taken as part.length.

like image 175
user7 Avatar answered Oct 05 '22 23:10

user7