简体   繁体   中英

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));

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 .

Something like this:

Map<String, String> map = Arrays.stream(str.split("-"))
                .map(s -> Pair.of(s.substring(0, 1), s.substring(1)))
                .collect(Collectors.toMap(Pair::getKey, Pair::getValue));

I've used Pair here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM