Java 一步加入带有分隔符的字符串列表元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4021851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Join String list elements with a delimiter in one step
提问by EugeneP
Is there a function like join that returns List's data as a string of all the elements, joined by delimiter provided?
是否有像 join 这样的函数将 List 的数据作为所有元素的字符串返回,由提供的分隔符连接?
List<String> join; ....
String join = list.join('+");
// join == "Elem 1+Elem 2";
or one must use an iterator to manually glue the elements?
还是必须使用迭代器手动粘合元素?
回答by Romain Linsolas
You can use the StringUtils.join()
method of Apache Commons Lang:
可以使用StringUtils.join()
Apache Commons Lang的方法:
String join = StringUtils.join(joinList, "+");
回答by nanda
回答by gahrae
Java 8...
爪哇 8...
String joined = String.join("+", list);
Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-
文档:http: //docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-
回答by Alex G
If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.
如果您只想记录元素列表,您可以使用 list toString() 方法,该方法已经连接了所有列表元素。
回答by marcello
If you are using Spring you can use StringUtils.join()
method which also allows you to specify prefix and suffix.
如果您使用的是 Spring,您可以使用StringUtils.join()
还允许您指定前缀和后缀的方法。
String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
"\n", "<value>", "</value>");
回答by Karim Oukara
You can use : org.springframework.util.StringUtils
;
你可以使用:org.springframework.util.StringUtils
;
String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);