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 !!
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.
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