在Java中使用定界符连接值列表的最优雅方法是什么? [英] What's the most elegant way to concatenate a list of values with delimiter in Java?

查看:164
本文介绍了在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.

推荐答案

这是我的版本:

另外的好处是:如果循环中的代码更复杂,则此方法将产生正确的结果,而无需复杂的if().

As an additional bonus: If your code in the loop is more complex, then this approach will produce a correct results without complex if()s.

还请注意,在现代CPU中,分配将仅在高速缓存中(或可能仅在寄存器中)进行.

Also note that with modern CPUs, the assignment will happen only in the cache (or probably only in a register).

结论:尽管此代码乍看之下很奇怪,但它具有许多优点.

Conclusion: While this code looks odd at first glance, it has many advantages.

这篇关于在Java中使用定界符连接值列表的最优雅方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆