Convert string representing key-value pairs to Map
Solution 1:
There is no need to reinvent the wheel. The Google Guava library provides the Splitter
class.
Here's how you can use it along with some test code:
package com.sandbox;
import com.google.common.base.Splitter;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
@Test
public void testQuestionInput() {
Map<String, String> map = splitToMap("A=4 H=X PO=87");
assertEquals("4", map.get("A"));
assertEquals("X", map.get("H"));
assertEquals("87", map.get("PO"));
}
private Map<String, String> splitToMap(String in) {
return Splitter.on(" ").withKeyValueSeparator("=").split(in);
}
}
Solution 2:
Java 8 to the rescue!
import static java.util.stream.Collectors.*;
Map<String, String> result = Arrays.stream(input.split(" "))
.map(s -> s.split("="))
.collect(Collectors.toMap(
a -> a[0], //key
a -> a[1] //value
));
NOTE: Assuming no duplicates. Otherwise look into the 3rd 'mergeFunction' argument.
Solution 3:
You don't need a library to do that. You just need to use StringTokenizer or String.split and iterate over the tokens to fill the map.
The import of the library plus its settings would be almost as big as the three lines of code needed to do it yourself. For example :
public static Map<String, String> convert(String str) {
String[] tokens = str.split(" |=");
Map<String, String> map = new HashMap<>();
for (int i=0; i<tokens.length-1; ) map.put(tokens[i++], tokens[i++]);
return map;
}
Note that in real life, the validation of the tokens and the string, highly coupled with your business requirement, would probably be more important than the code you see here.
Solution 4:
public static Map<String, String> splitToMap(String source, String entriesSeparator, String keyValueSeparator) {
Map<String, String> map = new HashMap<String, String>();
String[] entries = source.split(entriesSeparator);
for (String entry : entries) {
if (!TextUtils.isEmpty(entry) && entry.contains(keyValueSeparator)) {
String[] keyValue = entry.split(keyValueSeparator);
map.put(keyValue[0], keyValue[1]);
}
}
return map;
}
And now you can use it for different types of entries/key-values separators, just like this
Map<String, String> responseMap = splitToMap(response, " ", "=");