have a string like A=B&C=D&E=F, how to parse it into map?
I would use split
String text = "A=B&C=D&E=F";
Map<String, String> map = new LinkedHashMap<String, String>();
for(String keyValue : text.split(" *& *")) {
String[] pairs = keyValue.split(" *= *", 2);
map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
}
EDIT allows for padded spaces and a value with an =
or no value. e.g.
A = minus- & C=equals= & E==F
just use guava Splitter
String src="A=B&C=D&E=F";
Map map= Splitter.on('&').withKeyValueSeparator('=').split(src);
public class TestMapParser {
@Test
public void testParsing() {
Map<String, String> map = parseMap("A=B&C=D&E=F");
Assert.assertTrue("contains key", map.containsKey("A"));
Assert.assertEquals("contains value", "B", map.get("A"));
Assert.assertTrue("contains key", map.containsKey("C"));
Assert.assertEquals("contains value", "D", map.get("C"));
Assert.assertTrue("contains key", map.containsKey("E"));
Assert.assertEquals("contains value", "F", map.get("E"));
}
private Map<String, String> parseMap(final String input) {
final Map<String, String> map = new HashMap<String, String>();
for (String pair : input.split("&")) {
String[] kv = pair.split("=");
map.put(kv[0], kv[1]);
}
return map;
}
}
Split the string (either using a StringTokenizer
or String.split()
) on '&'. On each token just split again on '='. Use the first part as the key and the second part as the value.
It can also be done using a regex, but the problem is really simple enough for StringTokenizer
.
String t = A=B&C=D&E=F;
Map map = new HashMap();
String[] pairs = t.split("&");
//TODO 1) Learn generis 2) Use gnerics
for (String pair : pairs)
{
String[] kv = pair.split("=");
map.put(kv[0], kv[1]);
}