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));
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With