开发者

Convert List<String> to delimited String [duplicate]

开发者 https://www.devze.com 2023-03-10 18:55 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Java: convert List<String> to a join()d string
This question already has answers here: Closed 11 years ago.

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"


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号