class URLEncodedUtils {

  public static String format(final Map<String, Set<String>> parameters, final String encoding) {
    final StringBuilder result = new StringBuilder();

    for (Map.Entry<String, Set<String>> parameter : parameters.entrySet()) {
      final String encodedName = encode(parameter.getKey(), encoding);
      final Set<String> values = parameter.getValue();
      if (values == null || values.size() == 0) {
        result.append(encodedName);
        result.append(NAME_VALUE_SEPARATOR);
        result.append("");
      } else {
        for (String value : values) {
          final String encodedValue = value != null ? encode(value, encoding) : "";
          if (result.length() > 0) result.append(PARAMETER_SEPARATOR);
          result.append(encodedName);
          result.append(NAME_VALUE_SEPARATOR);
          result.append(encodedValue);
        }
      }
    }
    return result.toString();
  }

}