Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern to split string and store in HashMap Java 8

I want to split the below string and store it in a HashMap:

String currentString= "firstName-lastName-rollNum-departmentNum=firstName1-lastName1-rollNum1-departmentNum1"; 

I want my output to be store in map, like first string before hyphen (-)(firstName) and first string after (=)(firstName1),......... i.e.,

{firstName=firstName1,lastName=lastName1,rollNum=rollNum1,departmentNum=departmentNum1}

Below code doesn't work for my pattern:

Map<String,String> mapVal= null;
mapVal = Pattern.compile("\\s*=\\s*")
                .splitAsStream(currentString.trim())
                .map(s -> s.split("-", 2))
                .collect(Collectors.toMap(a -> a[0], a -> a.length>1? a[1]: ""));

Once I split the string I don't understand how I can get my required values together as shown above. I apologize if you don't get my question.

Thanks in advance !!

like image 311
Nain Avatar asked Dec 14 '22 13:12

Nain


1 Answers

A simpler approach is to just use split with standard arrays.

String[] keyValues = currentString.split("=", 2);
String[] keys = keyValues[0].split("-");
String[] values = keyValues[1].split("-", keys.length);
Map<String, String> map = IntStream.range(0, keys.length).boxed()
        .collect(Collectors.toMap(i -> keys[i], i -> values[i]));

There's no error checking in this but hopefully it'll give you the general idea.

like image 145
sprinter Avatar answered Dec 26 '22 18:12

sprinter