在一个步骤中使用分隔符连接 String 列表元素

是否有一个类似 join 的函数将 List 的数据作为 所有的元素,加上分隔符提供?

 List<String> join; ....
String join = list.join('+");
// join == "Elem 1+Elem 2";

还是必须使用迭代器手动粘合元素?

135660 次浏览

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

Or Joiner from Google Guava.

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

If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.

If you are using Spring you can use StringUtils.join() method which also allows you to specify prefix and suffix.

String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
"\n", "<value>", "</value>");

You can use : org.springframework.util.StringUtils;

String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);