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.

Sign up to request clarification or add additional context in comments.

Comments

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

  }
}

Comments

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.