Generic java function for creating maps from strings

Is there any general function (in apache commons or similar) for creating maps from strings with query parameters?

In particular:

Option a (Querystring)

s="a=1&b=3" => Utils.mapFunction(s, '&', '=') => (Hash)Map { a:1; b:3 } 

Option b (Cachecontrol-Header)

 s="max-age=3600;must-revalidate" => Utils.mapFunction(s, ';', '=') => (Hash)Map { max-age:3600; must-revalidate:true } 

I do not want to reinvent the wheel.

thanks

+6
java string map
source share
3 answers

It seems like a simple HashMap extension would do this:

 /** * Simple demo of extending a HashMap */ public class TokenizedStringHashMap extends HashMap<String, String> { void putAll(String tokenizedString, String delimiter) { String[] nameValues = tokenizedString.split(delimiter); for (String nameValue : nameValues) { String[] pair = nameValue.split("="); if (pair.length == 1) { // Duplicate the key name if there is only one value put(pair[0], pair[0]); } else { put(pair[0], pair[1]); } } } public static void main(String[] args) { TokenizedStringHashMap example = new TokenizedStringHashMap(); example.putAll("a=1&b=3", "&"); System.out.println(example.toString()); example.clear(); example.putAll("max-age=3600;must-revalidate", ";"); System.out.println(example.toString()); } } 
+1
source share

stringtomap

Try or browse the source code to see how it was implemented.

+2
source share

I don't think such a library exists, but if you want to override it with very little code, you can use "lambda-oriented libraries" like Guava or LambdaJ .

+1
source share

All Articles