java - 使用 += 构建从 null 开始的字符串的紧凑方法

标签 java

我想使用以下紧凑的方式构建一个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/

相关文章:

java - 将 JButton 控件添加到 JApplet 并且 JButton 填满整个屏幕

java - org.hibernate.SQLQuery 输出到对象

java - 转弯最少的最短路线

java - BACK 键未完成 Activity

JNLP 中的 java.security.properties

java - 自动从实例转到eclipse中的某个类

java - ImmutablePair 和 Pair 编译错误在反编译类中工作

java - Gradle缓存与存储库的哈希比较

java - 即使堆使用量远低于限制,Tomcat OOM 错误

java - 关于处理大量数据的建议