java collection implode

原创
2019/02/22 16:17
阅读数 340

With Java 8 you can do this without any third party library.

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

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部