[英]Converting ArrayList to a String & Split the results by a “,”
Is there a possible solution to convert an ArrayList into a String & split the results by a ",". 有没有可能的解决方案,将ArrayList转换为String并用“,”分隔结果。 So I'm trying to think would I add a "," to the string to use split string to split it in different places?
因此,我试图考虑是否要在字符串中添加“,”以使用拆分字符串将其拆分到不同的位置?
Like so? 这样吗
List<String> list = new ArrayList<String>();
list.add("person1,");
list.add("person2,");
list.add("person3,");
for ( String strs : list ) {
System.out.print(list);
strs.split(",");
}
I know for a fact that the for loop converts the list to a string. 我知道for循环会将列表转换为字符串。 I'm trying to achieve these results instead of just getting the ArrayList and having this
我正在尝试获得这些结果,而不是仅仅获取ArrayList并拥有这个
[Person1, Person2, Person3] [人1,人2,人3]
These are the results I'm trying to achieve. 这些是我想要达到的结果。 (As a string) not a ArrayList.
(作为字符串)不是ArrayList。
Person1, Person2, Person3 人1,人2,人3
Use String.join()
: 使用
String.join()
:
String.join(", ", list)
This, of course, only works on Java 8 or higher. 当然,这仅适用于Java 8或更高版本。
Seems as though you want to join the list, not split it: 似乎您想加入列表,而不是拆分列表:
String result = list.stream().collect(Collectors.joining(", "));
Or more elegantly: 或更优雅:
String result = String.join(", ", list);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.