Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse the string into map

Tags:

java

have a string like A=B&C=D&E=F, how to parse it into map?

like image 284
user496949 Avatar asked Mar 01 '11 10:03

user496949


2 Answers

just use guava Splitter

String src="A=B&C=D&E=F";
Map map= Splitter.on('&').withKeyValueSeparator('=').split(src);
like image 197
Geker Avatar answered Oct 02 '22 13:10

Geker


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
like image 32
Peter Lawrey Avatar answered Oct 02 '22 13:10

Peter Lawrey