是否有实用方法可以按给定字符串分隔列表?
Apache Common Lang 或 Spring Utils 中是否有类似以下内容的内容,或者您是否为此编写自己的 Util 方法?
List<String> list = new ArrayList<String>();
list.add("moo");
list.add("foo");
list.add("bar");
String enumeratedList = Util.enumerate(list, ", ");
assert enumeratedList == "moo, foo, bar";
我记得在php中使用implode
,这就是我搜索java的内容。
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
Is there something like the following in Apache Common Lang
or Spring Utils
or do you write your own Util method for this?
List<String> list = new ArrayList<String>();
list.add("moo");
list.add("foo");
list.add("bar");
String enumeratedList = Util.enumerate(list, ", ");
assert enumeratedList == "moo, foo, bar";
I remember the use of implode
in php, this is what i search for java.
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
StringUtils.join(Object[] array, String delimiter)
(来自 commons-lang)如下方式:You can use
StringUtils.join(Object[] array, String delimiter)
(from commons-lang) in the following way:Google 收藏集提供 Joiner 类,可以这样使用:
Google Collections provides the Joiner class, which can be used like this:
如果您不想依赖 commons-lang,那么实现起来非常简单。将列表转换为数组只是为了再次将其连接为字符串也不是很好。相反,只需迭代您的集合即可。比使用 Collection 更好的是使用 Iterable,它可以处理任何可以迭代的东西(甚至是某种长度未知的流或集合)。
例子:
It's pretty trivial to inplement if you don't want a dependency on commons-lang. It's also not great to convert a List to an Array simply to join it again into a String. Instead just iterate over your collection. Even better than using Collection is using Iterable which handles anything which can be iterator over (even some sort of stream or Collection of unknown length).
Example: