0

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?

Matt Ryall
  • 9,977
  • 5
  • 24
  • 20
J_Coder
  • 707
  • 5
  • 14
  • 32

1 Answers1

6

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("_"));
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 1
    From title of the question it seems me OP is using a `List`, so `map` could be omitted. – dariosicily Aug 27 '20 at 06:47
  • 1
    @dariosicily: the whole second line is unnecessary if it's really a `List`, which is why I put the simpler version first. – Joachim Sauer Aug 27 '20 at 08:07
  • 1
    Agree with you about everything, my consideration was based about the fact OP was trying to solve the problem using streams probably not being aware of `String.join`. – dariosicily Aug 27 '20 at 08:18
  • 1
    @dariosicily: which is literally what I've written in the first paragraph of my answer. If they don't read the text, but just copy the code, then no amount of clarification will help them. – Joachim Sauer Aug 27 '20 at 12:19