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

前端 未结 30 2194
耶瑟儿~
耶瑟儿~ 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:12

    In Java 8 you can use String.join():

    List<String> list = Arrays.asList("foo", "bar", "baz");
    String joined = String.join(" and ", list); // "foo and bar and baz"
    

    Also have a look at this answer for a Stream API example.

    0 讨论(0)
  • 2020-11-22 06:16

    Java 8

    stringCollection.stream().collect(Collectors.joining(", "));
    
    0 讨论(0)
  • 2020-11-22 06:16
    //Note: if you have access to Java5+, 
    //use StringBuilder in preference to StringBuffer.  
    //All that has to be replaced is the class name.  
    //StringBuffer will work in Java 1.4, though.
    
    appendWithDelimiter( StringBuffer buffer, String addition, 
        String delimiter ) {
        if ( buffer.length() == 0) {
            buffer.append(addition);
        } else {
            buffer.append(delimiter);
            buffer.append(addition);
        }
    }
    
    
    StringBuffer parameterBuffer = new StringBuffer();
    if ( condition ) { 
        appendWithDelimiter(parameterBuffer, "elementName", "," );
    }
    if ( anotherCondition ) {
        appendWithDelimiter(parameterBuffer, "anotherElementName", "," );
    }
    
    //Finally, to return a string representation, call toString() when returning.
    return parameterBuffer.toString(); 
    
    0 讨论(0)
  • 2020-11-22 06:17

    And a minimal one (if you don't want to include Apache Commons or Gauva into project dependencies just for the sake of joining strings)

    /**
     *
     * @param delim : String that should be kept in between the parts
     * @param parts : parts that needs to be joined
     * @return  a String that's formed by joining the parts
     */
    private static final String join(String delim, String... parts) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < parts.length - 1; i++) {
            builder.append(parts[i]).append(delim);
        }
        if(parts.length > 0){
            builder.append(parts[parts.length - 1]);
        }
        return builder.toString();
    }
    
    0 讨论(0)
  • 2020-11-22 06:17

    Your approach is not too bad, but you should use a StringBuffer instead of using the + sign. The + has the big disadvantage that a new String instance is being created for each single operation. The longer your string gets, the bigger the overhead. So using a StringBuffer should be the fastest way:

    public StringBuffer appendWithDelimiter( StringBuffer original, String addition, String delimiter ) {
            if ( original == null ) {
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(addition);
                    return buffer;
            } else {
                    buffer.append(delimiter);
                    buffer.append(addition);
                    return original;
            }
    }
    

    After you have finished creating your string simply call toString() on the returned StringBuffer.

    0 讨论(0)
  • 2020-11-22 06:18

    The Google's Guava library has com.google.common.base.Joiner class which helps to solve such tasks.

    Samples:

    "My pets are: " + Joiner.on(", ").join(Arrays.asList("rabbit", "parrot", "dog")); 
    // returns "My pets are: rabbit, parrot, dog"
    
    Joiner.on(" AND ").join(Arrays.asList("field1=1" , "field2=2", "field3=3"));
    // returns "field1=1 AND field2=2 AND field3=3"
    
    Joiner.on(",").skipNulls().join(Arrays.asList("London", "Moscow", null, "New York", null, "Paris"));
    // returns "London,Moscow,New York,Paris"
    
    Joiner.on(", ").useForNull("Team held a draw").join(Arrays.asList("FC Barcelona", "FC Bayern", null, null, "Chelsea FC", "AC Milan"));
    // returns "FC Barcelona, FC Bayern, Team held a draw, Team held a draw, Chelsea FC, AC Milan"
    

    Here is an article about Guava's string utilities.

    0 讨论(0)
提交回复
热议问题