2

String str="ABCD 1 key1=value1 key2=value2 key3=value3";

I want to convert the above string into the key-value pair

Map<String, String> map = new HashMap<String, String>();

if i want to access the key1 then it should return the value1 for eg: map.get("key1") should return value1.

please help me with an efficient way to convert the same into the hashmap.

Taher Mahodia
  • 194
  • 2
  • 13

2 Answers2

4

Probably the safest approach is to define a regex pattern for a key/value pair, and then iterate over your string, applying that pattern. In this, case we can try using the following pattern:

\b([^\s]+)=([^\s]+)\b

The key and value will be made available as the first and second capture group, respectively. Some slight finessing was required, because not all of your string is key values (i.e. the leading content does not belong in the final map).

Map<String, String> map = new HashMap<>();
String str="ABCD 1 key1=value1 key2=value2 key3=value3";
String pattern = "\\b([^\\s]+)=([^\\s]+)\\b";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);

while (m.find()) {
    System.out.println("Found a key/value: (" + m.group(1) + ", " + m.group(2) + ")");
    map.put(m.group(1), m.group(2));
}

The above code snippet outputs the following:

Found a key/value: (key1, value1)
Found a key/value: (key2, value2)
Found a key/value: (key3, value3)

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I didn't downvote, but I guess someone did because you answered a question that seems to be a duplicate. – domsson Dec 15 '17 at 06:13
  • @domsson Actually, the pattern needed here is different, perhaps not an exact duplicate, but yes in theory the OP should be able to solve this just using that link. – Tim Biegeleisen Dec 15 '17 at 06:14
-1

You can try to write your code like below

public static void main(String[] args) {
    String str = "key1=value1 key2=value2 key3=value3";
    Map<String, String> map = new HashMap<String, String>();

    String[] strArray = str.split(" ");
    for (int i = 0; i < strArray.length; i++) {

        String data = strArray[i];

        String[] keyValue = data.split("=");

        map.put(keyValue[0], keyValue[1]);

    }

    System.out.println(map.get("key1"));

}
  • This won't work with the OP's data as it contains text other than keys and values. Not my downvote. – Tim Biegeleisen Dec 15 '17 at 06:27
  • This code won't work for the sample data from the question. – m. vokhm Dec 15 '17 at 06:28
  • @m.vokhm he asked us to cut the ABCD 1 from the sample data – Joginder Kumar Dec 15 '17 at 08:03
  • @JoginderKumar He did not ask to remove them manually. He showed that there may be substrings other than `key=value` and these substrings should be ignored, and he confirmed this by accepting the other answer, with the code that behaves like I said. Your code will throw `NullPointerException` on such an input. – m. vokhm Dec 15 '17 at 11:33