我想使用以下紧凑的方式构建一个String
:
String attributes = null;
for (Map.Entry<String, String> kvp : attrs.entrySet())
attributes += (kvp.getKey() + "='" + kvp.getValue() +"' ");
但结果是一个字符串,内容为:nullattr1='val1' attr2='val2' attr3='val3'
。我假设这是由于对当前值为 null 的 String
执行 +=
操作而发生的。有没有紧凑的方法可以做到这一点而不必每次通过循环检查 attributes
是否为空?
最佳答案
String attributes = "";
将允许这样做,并且适用于 5 或 20 个值的小型 map 。对于较大的 map ,StringBuilder 或 ~Buffer 是可行的方法:
StringBuffer sb = new StringBuffer (estimatedSize);
for (X x: xx)
sb.append (foo).append (bar).append (baz);
String attributes = sb.toString ();
关于java - 使用 += 构建从 null 开始的字符串的紧凑方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10306686/