tags:

views:

80

answers:

3

Is there any common function (in apache commons or similar) to make maps from query-parameter-like strings?

To specific:

Variant a (Querystring)

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

Variant b (Cachecontrol-Header)

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

I don't want to reinvent the wheel.

Thanks

+1  A: 

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

Benoit Courtine
+1  A: 

stringtomap

Try it out or browse the source code to see how it has been implemented.

dogbane
+1  A: 

Seems that a simple extension of HashMap would do it:

/**
 * 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());

  }
}
Gary Rowe