在Java中使用定界符连接值列表的最优雅方法是什么? [英] What's the most elegant way to concatenate a list of values with delimiter in Java?
问题描述
我从未发现过一种整洁的方法来进行以下操作.
I have never found a neat(er) way of doing the following.
说我有一个字符串列表/数组.
Say I have a list/array of strings.
abc
def
ghi
jkl
我想将它们连接成一个用逗号分隔的字符串,如下所示:
And I want to concatenate them into a single string delimited by a comma as follows:
abc,def,ghi,jkl
在Java中,如果我编写这样的内容(请原谅语法),
In Java, if I write something like this (pardon the syntax),
String[] list = new String[] {"abc","def","ghi","jkl"};
String str = null;
for (String s : list)
{
str = str + s + "," ;
}
System.out.println(str);
我会得到
abc,def,ghi,jkl, //Notice the comma in the end
所以我必须按如下方式重写上述for循环
So I have to rewrite the above for loop as follows
...
for (int i = 0; i < list.length; i++)
{
str = str + list[i];
if (i != list.length - 1)
{
str = str + ",";
}
}
...
这可以在Java中以更优雅的方式完成吗?
Can this be done in a more elegant way in Java?
我当然会使用StringBuilder/Buffer来提高效率,但是我想举例说明这种情况,不要太冗长.优雅地说,我的意思是避免在循环内进行ugly(?)if
检查的解决方案.
I would certainly use a StringBuilder/Buffer for efficiency, but I wanted to illustrate the case in point without being too verbose. By elegant, I mean a solution that avoids the ugly(?) if
check inside the loop.