Remove Last Comma

  • I want to join strings together, but when doing this it often happens that there is a comma too many, and therefore I need to remove that comma. In this code, I use the substring to delete the two last characters.

    How can this become more elegant?

    List<String> paramList = new ArrayList<String>( );
    paramList.add( "param1" );
    paramList.add( "param2" );

    StringBuilder result = new StringBuilder();
    for ( String p : paramList )
    result.append( p ).append( ", " );

    String withoutLastComma = result.substring( 0, result.length( ) - ", ".length( ) );
    System.err.println( withoutLastComma );

    How about instead of adding comma and then removing it just not add comma to the last item? using the index based approach would have been fine. for (int i = 0; i < paramList.size()-1; i++) { result.append( p ).append( ", " ); }

    Swapping the order of appends--`result.append(", ").append(p)`--allows you to use the simpler extraction: `result.substring(", ".length())`

    If you don't want to use an external library, your solution provides the best readability imo. From all possibilities, I always use this one (although usually with `result.deleteCharAt(result.length)` which doesn't fit in here)

    Rather than using any external library for this purpose, it is better to use Streams library provided in Java 8. Use this - **;**

  • One may use string utility methods such as StringUtil.join to concatenate elements in an array or a collection object. Consult the StringUtil API's StringUtil.join entry.

    For example:

    StringUtils.join(["a", "b", "c"], "--")  // => "a--b--c"

    I will add a tool library. First i have to check the differences between apache commons and google guave.

    I don't see how something this simple can justify adding a library.

    @Wes: If you are working with critical production code and do not want to take on unnecessary dependencies (or have a policy requirement not to use external libraries) and have the time to write/test/debug/optimize your own methods, then by all means, roll your own. I made the assumption that OP is looking for a simple solution for a non-critical task.

    Guava has `Joiner`: `Joiner.on(", ").join(paramList)`. It provides helpful options such as skipping `null` values, too. Oops, already an answer.

    Java 8 now also has a `String.join()` method, see my answer below.

    this corresponds to php's `implode()` function, I guess

    @Athas: By repeating that statement for every new utility method you end up with a self made copy of all the methods of that library. And I don't even ask for the unit tests that you wrote for "something this simple".

    Rather than using any external library for this purpose, it is better to use Streams library provided in Java 8. Use this -;

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used