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"
Approach: This can be achieved with the help of join() method of String as follows. Get the List of String. Form a comma separated String from the List of String using join() method by passing comma ', ' and the list as parameters. Print the String.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
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());
If you don't mind using the StringUtils library provided by apache, you could do:
// Output is "a,b,c"
StringUtils.join(["a", "b", "c"], ',');
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With