A compact way to build a line starting at zero using + =

I would like to use the following compact construction method String:

String attributes = null;
for (Map.Entry<String, String> kvp : attrs.entrySet())
  attributes += (kvp.getKey() + "='" + kvp.getValue() +"' ");

but the result is a line that says nullattr1='val1' attr2='val2' attr3='val3'. I assume that this occurs as a result of performing an operation +=on Stringwhose current value is null. Is there a compact way to do this without checking if it matters attributesevery time through the loop?

+3
source share
7 answers

Do this for initialization Stringat the beginning of the code:

String attributes = "";
+4
source
String attributes = "";

will allow this, and will be good for small cards of 5 or 20 values. For large cards, StringBuilder or ~ Buffer is the way to go:

StringBuffer sb = new StringBuffer (estimatedSize);
for (X x: xx) 
     sb.append (foo).append (bar).append (baz);
String attributes = sb.toString ();
+7

null .

"" null:

String attributes = "";
...

'...' ,

String attributes = "";
for (Map.Entry<String, String> kvp : attrs.entrySet())
  attributes += kvp + " ";

, StringBuilder String:

StringBuilder attributes = new StringBuilder();
for (Map.Entry<String, String> kvp : attrs.entrySet())
    attributes.append(kvp.getKey())
              .append("='")
              .append(kvp.getValue())
              .append("' ");
+3

String attributes = "";
for (Map.Entry kvp : attrs.entrySet())
  attributes += (kvp.getKey() + "='" + kvp.getValue() +"' ");
+2

, String attributes = null;, String attributes = "";

, StringBuilder, , - , + = .

+1

, String , , , StringBuilder, .

public String getString(Map<String, String> attrs)  {
    StringBuilder bldr = new StringBuilder();
    for (Map.Entry<String, String> kvp : attrs.entrySet()) {
        bldr.append(String.format("'%s'='%s' ", kvp.getKey(), kvp.getValue()));
    }
    return bldr.toString();
}
+1

attributes :

String attributes = "";

Edited

0

All Articles