Pattern to split string and store in HashMap Java 8

  • A+

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


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: