Java – Convert List to delimited String

javaliststring

Possible Duplicate:
Java: convert List<String> to a join()d string

Having this:

List<String> elementNames = Arrays.asList("h1", "h2", "h3", "h4", "h5", "h6");

What is an elegant way to get String with a custom delimiter, like so:

"h1,h2,h3,h4,h5,h6"

Best Solution

StringBuilder sb = new StringBuilder();

for(String s: elementnames) {
   sb.append(s).append(',');
}

sb.deleteCharAt(sb.length()-1); //delete last comma

String newString = sb.toString();

Update: Starting java 8, you can obtain the same results using:

    List<String> elementNames = Arrays.asList("1", "2", "3");

    StringJoiner joiner = new StringJoiner(",", "", "");
    elementNames.forEach(joiner::add);

    System.out.println(joiner.toString());