user3628645
user3628645

Reputation: 33

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

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.

Upvotes: 2

Views: 2091

Answers (2)

Dilip Chauhan
Dilip Chauhan

Reputation: 177

This solution you can try

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SplitTest {
public static void main(String[] args) {
    String str="Reference=R1,R2 GroupId=G01 Date=12/02/2017 15:25 GroupId2=G02 Date=12/02/2017 30:25 Date=12/02/2017 30:25 Date=12/02/2017 30:25 GroupId3=G03";
    String[] split = str.split(" ");
    List<String> asList = Arrays.asList(split);
    List<String> newList = new ArrayList<>();
    for (int i = 0; i < asList.size();) {
        if(asList.get(i).toString().startsWith("Date")){
            String str1 = asList.get(i);
            String str2 = asList.get(i+1);
            newList.add(str1+" "+str2);
            i=i+2;
        }else{
            newList.add(asList.get(i));
            ++i;
        }
    }
    System.out.println(newList.toArray());
}

}

Output

Reference=R1,R2
GroupId=G01 
Date=12/02/2017 15:25 
GroupId2=G02
Date=12/02/2017 30:25 
Date=12/02/2017 30:25 
Date=12/02/2017 30:25 
GroupId3=G03

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522731

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.

Upvotes: 3

Related Questions