1

I have Java Commandline App where I'm using parameters when starting the .jar file. Parameters looks like

--exclude parent1=child1,child2;parent2=child3;parent3 

I want to convert the parameters to HashMap<String, String[]> where the key=parent1 and value=[child1,child2]

I tried with Streams and split() function but I can't convert the child strings to Array of Strings

Arrays.stream(gotData.split(";"))
            .map(s -> s.split("="))
            .collect(Collectors.toMap(s -> s[0], s -> s[1].split(",")));
YCF_L
  • 49,027
  • 13
  • 75
  • 115
M.Matt
  • 69
  • 5
  • 1
    Possibly related: [How to group into map of arrays?](https://stackoverflow.com/questions/53695027/how-to-group-into-map-of-arrays) – Ole V.V. Jan 17 '21 at 13:13

1 Answers1

3

To solve your issue you have to check each time your data, because in the collect part you try to split s[1] for parent3 which not exist, to avoid this issue, you can check the length of array before like so

Arrays.stream(gotData.split(";"))
    .map(s -> s.split("="))
    .collect(Collectors.toMap(s -> s[0], s -> {
        // If there size of array great than 1 mean there are children.
        if (s.length > 1) {
            return s[1].split(",");
        }
        // Else just return an empty array.
        return new String[0];
    }));

If you have other cases, maybe you need to add other conditions to this code to avoid any kind of errors.


To show the response:

response.forEach((k, v) -> System.out.println(k + " - " + Arrays.toString(v)));

Otputs

parent1 - [child1, child2]
parent3  - []
parent2 - [child3]
YCF_L
  • 49,027
  • 13
  • 75
  • 115