更新时间:2023-02-03 09:21:02
使用 Java 8,您无需任何第三方库即可完成此操作.
With Java 8 you can do this without any third party library.
如果您想加入一个字符串集合,您可以使用新的 String.join() 方法:
If you want to join a Collection of Strings you can use the new String.join() method:
List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
如果您的集合类型不是字符串,您可以使用带有 加入收藏家:
If you have a Collection with another type than String you can use the Stream API with the joining Collector:
List<Person> list = Arrays.asList(
new Person("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);
String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(", ")); // "John, Anna, Paul"
StringJoiner
类可以也很有用.
The StringJoiner
class may also be useful.