将List <string>转换为分隔的String </string>

时间:2011-06-05 18:11:52

标签: java string list

  

可能重复:
  Java: convert List<String> to a join()d string

有这个:

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

使用自定义分隔符获取String的优雅方法是什么,如下所示:

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

2 个答案:

答案 0 :(得分:37)

StringBuilder sb = new StringBuilder();

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

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

String newString = sb.toString();

更新:启动java 8,您可以使用以下方法获得相同的结果:

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

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

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

答案 1 :(得分:27)

如果您不介意使用apache提供的StringUtils库,您可以这样做:

// 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