Search code examples
javasplithashmapjava-stream

Split String into Map using Java Streams


I want to split the following String and store it into a Map.

String = "key_a:<value_a1>\r\n\r\nkey_b:<value_b1>\r\n\r\nkey_c:<value_c1, value_c2, value_c3>"

The string can have line breaks in between the pairs. A key can have multiple values that are separated by a , and begin with a < and end with a >.

Now this String needs to be converted to a Map<String, List<String>>.

The structure of the map should look like this:

key_a={value_a1}, 
key_b={value_b1}, 
key_c={value_c1, value_c2, value_c3}

I currently only have the logic for splitting apart the different key-value-pairs from each other, but I don't know how to implement the logic that splits the values apart from each other, removes the brackets and maps the attributes.

String strBody = "key_a:<value_a1>\r\n\r\nkey_b:<value_b1>\r\n\r\nkey_c:<value_c1, value_c2, value_c3>"

Map<String, List<String>> map = Pattern.compile("\\r?\\n")
            .splitAsStream(strBody)
            .map(s -> s.split(":"))
               //...logic for splitting values apart from each other, removing <> brackets and storing it in the map           
            )

Solution

  • You can filter the arrays having two values and then use Collectors.groupingBy to group the elements into Map, You can find more examples here about groupingBy and `mapping

     Map<String, List<String>> map = Pattern.compile("\\r?\\n")
                .splitAsStream(strBody)
                .map(s -> s.split(":"))
                .filter(arr -> arr.length == 2)
                .collect(Collectors.groupingBy(arr -> arr[0],
                        Collectors.mapping(arr -> arr[1].replaceAll("[<>]", ""), 
                                Collectors.toList())));