2

I have this method:

    public String nodePropertyGenerator(Map<String,Object> properties){
    String prop="";
    for(Map.Entry<String, Object> entry : properties.entrySet()) {
        prop += entry.getKey() + ":'" +entry.getValue()+"' ,";
        Iterator iterator = properties.entrySet().iterator(); 
    }
    return prop;
}

I want to this method return a string like this:

name:'hossein' , age:'24' , address:'khorram'

so I want to check if my map's element be end element , it remove "," from end of string. how to do that. please help me. thanks

3 Answers3

4

One way is to add a boolean variable, set it to true before entering the loop, and use it to decide if you need a comma before adding the next component, like this:

boolean isFirst = true;
StringBuilder res = new StringBuilder();
for (Map.Entry<String, Object> entry : properties.entrySet()) {
    if (!isFirst) {
        res.append(", ");
    }
    isFirst = false;
    res.append(entry.getKey());
    res.append(":'");
    res.append(entry.getValue());
    res.append("'");
}

Note that using the concatenation operator on immutable strings in a loop is inefficient. You should use StringBuilder instead.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You can't tell whether the current iteration is the last one. I suggest you use a StringBuilder instead of repeated string concatenation, then just trim the length at the end:

StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Object> entry : properties.entrySet()) {
    builder.append(entry.getKey())
           .append(":'")
           .append(entry.getValue())
           .append("' ,");
}
if (builder.length() > 0) {
    builder.setLength(builder.length() - 2);
}
return builder.toString();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Java 8 has a class to do this: java.util.StringJoiner

You would use it like this:

StringJoiner stringJoiner = new StringJoiner("' ,");
for(Map.Entry<String, Object> entry : properties.entrySet()) {
    stringJoiner.add(entry.getKey() + ":'" +entry.getValue());
}
return stringJoiner.toString();

Or alternatively you could use a Stream to do this:

return properties.entrySet().stream()
                 .map(entry -> entry.getKey() + ":'" +entry.getValue())
                 .collect(Collectors.joining("' ,"));
fabian
  • 80,457
  • 12
  • 86
  • 114