6

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

3 Answers 3

2

stringtomap

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

1

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

  }
}
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.