我有两个相同功能的实现,它们如下所示。
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);
}
第二个
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();
}
此方法的每个版本都采用保证不为空的字符串映射并从中创建一个字符串。字符串以键开头,后跟 - 然后是值。这些对中的每一对都由_分隔。
key1-value1_key2-value2_key3-value3_......
我的两个选项是检查字符串是否为空,而不是放置 _ 分隔符并保存自己在末尾创建子字符串。或者不做检查,在循环结束时附加 _,然后使用子字符串删除导致的额外 _。
我很好奇对于任意大的地图哪个更有效。