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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:32:59  来源:igfitidea点击:

Join String list elements with a delimiter in one step

java

提问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

Or Joinerfrom Google Guava.

或来自 Google Guava 的Joiner

Joiner joiner = Joiner.on("+");
String join = joiner.join(joinList);

回答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);