英文:
Converting List<String> to String using java streams
问题
我在一个 ArrayList
中有一些值,如 Value1,Value2,Value3
。现在我需要使用 Java Streams
将它们以 Value1_Value2_Value3
的形式作为单个 String
返回。
我尝试了以下代码,但没有成功:
myList.stream().map((s) -> s + "_").toString();
我还尝试了 collect(toList());
,但我不确定如何进一步转换为 String
。
请问我该如何实现?
英文:
I have values in an ArrayList
as Value1, Value2, Value3
.
Now i need to return them in a way as a Single String
as Value1_Value2_Value3
using Java Streams
.
I've tried this but it didn't work
myList.stream().map((s)->s+"_").toString();
I've also tried collect(toList());
but I'm not sure how to proceed further to convert it to a String
.
How can I do it?
答案1
得分: 6
如果您的myList
已经包含String
(或任何其他CharSequence
),则根本不需要使用流,只需调用String.join
:
String joined = String.join("_", myList);
否则,您可以使用Collectors.joining
从任何旧流中生成String
:
String joined = myList.stream().map(Object::toString).collect(Collectors.joining("_"));
英文:
If your myList
already contains String
(or any other CharSequence
), then you don't need streams at all, simply call String.join
:
String joined = String.join("_", myList);
Otherwise you can use Collectors.joining
to produce String
from any old stream:
String joined = myList.stream().map(Object::toString).collect(Collectors.joining("_"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论