What's the best way to build a string of delimited items in Java?

前端 未结 30 2757
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be i

30条回答
  •  面向向阳花
    2020-11-22 06:34

    You're making this a little more complicated than it has to be. Let's start with the end of your example:

    String parameterString = "";
    if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
    if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );
    

    With the small change of using a StringBuilder instead of a String, this becomes:

    StringBuilder parameterString = new StringBuilder();
    if (condition) parameterString.append("elementName").append(",");
    if (anotherCondition) parameterString.append("anotherElementName").append(",");
    ...
    

    When you're done (I assume you have to check a few other conditions as well), just make sure you remove the tailing comma with a command like this:

    if (parameterString.length() > 0) 
        parameterString.deleteCharAt(parameterString.length() - 1);
    

    And finally, get the string you want with

    parameterString.toString();
    

    You could also replace the "," in the second call to append with a generic delimiter string that can be set to anything. If you have a list of things you know you need to append (non-conditionally), you could put this code inside a method that takes a list of strings.

提交回复
热议问题