在java中,将ArrayList转换为字符串String的最佳方法

在Java 8或更高版本中:

String listString = String.join(", ", list);
Returns a new String composed of copies of the {@code CharSequence elements} joined together with a copy of the specified {@code delimiter}.
String message = String.join("-", "Java", "is", "cool"); 
 **// message returned is: "Java-is-cool"**
 List<String> strings = new LinkedList<>();
strings.add("Java");strings.add("is");
 strings.add("cool");
String message = String.join(" ", strings);

**// message returned is: "Java is cool"**

如果list不是String类型,则可以使用collector:

String listString = list.stream().map(Object::toString)
                        .collect(Collectors.joining(", "));
Returns a {@code Collector} that concatenates the input elements,
separated by the specified delimiter, in encounter order.

请大家批评 指正 ! 谢谢

发布了45 篇原创文章 · 获赞 6 · 访问量 2087

猜你喜欢

转载自blog.csdn.net/qq_22583191/article/details/103489381