How to Split a string by space and store in form of key value in map in Java?

user3628645 :

I have a String of consisting of parameters separated by space of the form:

Reference=R1,R2 GroupId=G01 Date=12/02/2017 15:25.

I need to split the string in such a way that left hand side of the '=' token is key and the one to the right is the value which will be stored in a map. Eg.

Key         Value
Reference    R1,R2
GroupId      G01
Date         12/02/2017 15.25

I did try splitting the string by using String.split(" ") but the date parameter has a space between date and time which will disturb the arrangement.

Tim Biegeleisen :

We can try splitting on the following regex pattern:

\s+(?=[^=]+=)

This says to split on any amount of whitespace, which is immediately followed by a key plus =. Note that this split does not consume anything other than the separating whitespace, turning out keys with values intact.

Map<String, String> map = new HashMap<>();
String input = "Reference=R1,R2 GroupId=G01 Date=12/02/2017 15:25";
String[] parts = input.split("\\s+(?=[^=]+=)");
for (String part : parts) {
    map.put(part.split("=")[0], part.split("=")[1]);
    System.out.println(part);
}

This outputs:

Reference=R1,R2
GroupId=G01
Date=12/02/2017 15:25

The only extra step I did not explicitly test here is generation of the map with its keys and values.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134373&siteId=1
Recommended