将列表<字符串>转换为分隔字符串

2022-09-03 08:27:38

可能的重复:
Java:将 List<String> 转换为 join()d 字符串

有这个:

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

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

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

答案 1
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());

答案 2

如果您不介意使用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