Pattern to split string and store in HashMap Java 8

Viewed 2446

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

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

As shown in this answer, a plain array based operation may be much simpler here.

But if you insist on a Stream solution, it may look like

Map<String,String> mapVal= Stream.of(currentString)
    .map(s0 -> Arrays.stream(s0.split("\\s*=\\s*", 2))
        .map(s1 -> s1.split("-")).toArray(String[][]::new))
    .flatMap(a -> IntStream.range(0, a[0].length)
        .mapToObj(i -> new String[]{ a[0][i], i < a[1].length? a[1][i]: "" }))
    .collect(Collectors.toMap(a -> a[0], a -> a[1]));

Another solution :

String[] arr = Arrays.toString(currentString.split("="))
                     .replaceAll("[\\[\\]]", "").replaceAll(",", "-")
                     .split("-");

Map<String, String> collect = IntStream.range(0, arr.length / 2).boxed()
                 .collect(Collectors.toMap(i -> arr[i], i -> arr[i + arr.length / 2]));

Here we split the string first based on =, then we use the .toString() to remove all occurrences of ] and[ from the String. Now we replace , with - so we can split the resulting String based on -

After the first statement the array arr looks like :

[firstName, lastName, rollNum, departmentNum, firstName1, lastName1, rollNum1, departmentNum1]

Now all we need to do is to iterate over the resulting array(arr) upto the mid-point(arr.length / 2) and map it using Collectors.toMap

Other way would be like this:

Pattern pattern = Pattern.compile("\\s*=\\s*");
int index = currentString.indexOf("=");
Map<Boolean, List<String>> map = pattern
            .splitAsStream(currentString.trim())
            .flatMap(s -> Stream.of(s.split("-")))
            .collect(partitioningBy(s -> currentString.indexOf(s) > index));

this step result is:

{
  false=[firstName, lastName, rollNum, departmentNum],

  true=[firstName1, lastName1, rollNum1, departmentNum1]
}

and then convert previous result to final result:

IntStream.range(0, map.get(true).size())
            .boxed()
            .collect(toMap(i -> map.get(false).get(i), i -> map.get(true).get(i)));
public static Map<String, String> toMap(String str) {
    String[] arr = str.split("[-=]");
    Map<String, String> map = new LinkedHashMap<>();

    for (int i = 0, j = arr.length / 2; j < arr.length; i++, j++)
        map.put(arr[i], arr[j]);

    return map;
}
Related