mohit
mohit

Reputation: 67

Convert a String to a Map

I have a string with a comma separated values "name1=John,name2=Jim,name3=Tina" (this can grow) which i want to convert in a Map with a key value pair as {name1=John,name2=Jim,name3=Tina}.

String names = "name1=John,name2=Jim,name3=Tina";

Map<String, String> map = Pattern.compile("\\s*-\\s*")
                           .splitAsStream(externalResourcePath.trim())
                           .map(s -> s.split(","))
                           .collect(Collectors.toMap(p -> p[0], p -> p[1]));

I am getting output as {name1=John=name2=Jim} instead I want the output as {name1=John,name2=Jim,name3=Tina}

Upvotes: 1

Views: 85

Answers (1)

THe_strOX
THe_strOX

Reputation: 717

You need to split by "=" again to separate the key and value.

Map<String, String> map = Arrays.stream(names.split(","))
            .map(s -> s.split("="))
            .collect(Collectors.toMap(array -> array[0], array -> array[1]));

Upvotes: 2

Related Questions