I have two implementations of the same functionality they look as follows.
private String mapToString(Map<String, String> map)
throws UnsupportedEncodingException
{
if(map.isEmpty())
{
throw new IllegalArgumentException("Map cannot be empty");
}
StringBuilder sb = new StringBuilder();
for(Map.Entry<String, String> pair : map.entrySet())
{
if(pair.getKey() == null)
{throw new IllegalArgumentException("Invalid parameter:" +
" Parameters key is null");}
if(pair.getValue() == null)
{throw new IllegalArgumentException("Invalid parameter:" +
" Parameters value is null");}
// Because the map cannot be empty and can be of arbitrary size it
// is it more efficient to append the _ at the end of each cycle and
// remove the extra _ when the string is done being built.
sb.append(URLEncoder.encode(pair.getKey(), "UTF-8"));
sb.append('-');
sb.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
sb.append('_');
}
String result = sb.toString();
// Remove the extra _
return result.substring(0, result.length() - 1);
}
and the second one
private String mapToString(Map<String, String> map)
throws UnsupportedEncodingException
{
if(map.isEmpty())
{
throw new IllegalArgumentException("Map cannot be empty");
}
StringBuilder sb = new StringBuilder();
for(Map.Entry<String, String> pair : map.entrySet())
{
if(pair.getKey() == null)
{throw new IllegalArgumentException("Invalid parameter:" +
" Parameters key is null");}
if(pair.getValue() == null)
{throw new IllegalArgumentException("Invalid parameter:" +
" Parameters value is null");}
if(sb.length() != 0)
{
sb.append('_');
}
sb.append(URLEncoder.encode(pair.getKey(), "UTF-8"));
sb.append('-');
sb.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return sb.toString();
}
Each version of this method takes a map of strings that is guaranteed to not be empty and creates a string from them. The string starts with the key followed by a - then the value. Each of these pairs are separated by a _.
key1-value1_key2-value2_key3-value3_......
My two options are to check the to see if string is empty and not place the _ separator and save myself creating a substring at the end. Or do not do a check, append the _ at the end of the cycle and then use a substring to remove the extra _ that results.
I am curious as to which would be more efficient for an arbitrarily large map.