使用Java流将List<String>转换为String

huangapple go评论76阅读模式
英文:

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)-&gt;s+&quot;_&quot;).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(&quot;_&quot;, myList);

Otherwise you can use Collectors.joining to produce String from any old stream:

String joined = myList.stream().map(Object::toString).collect(Collectors.joining(&quot;_&quot;));

huangapple
  • 本文由 发表于 2020年8月27日 14:35:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63610430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定