Convert a List<String> in a String with all the values of the List comma separated using Java 8 is really straightforward.
Let’s have a look on how to do that.
Java 8 (or above)
We simply can write String.join(..), pass a delimiter and an Iterable, then the new StringJoiner will do the rest:
In case we are working with a stream we can write as follow and still have the same result:
Note: you can statically import java.util.stream.Collectors.joining if you prefer just typing joining(“,”).
Java 7
For the old times’ sake, let’s have a look at Java 7 implementation.
As you can see it’s much more verbose and easier to make mistakes like forgetting to remove the last comma. You can implement this in several ways - for example by moving the logic that removes the last comma inside the for loop - but none will be so explicative and immediate to understand as the declarative solution expressed in Java 8.
The focus should be on what you want to do - joining a List of String - not on how.
Java 8: Manipulate String before joining
Before joining you can manipulate your String as you prefer by using map() or cutting some String out by using filter(). I’ll cover those topics in further articles. Meanwhile, this a straightforward example on how to transform the whole String in upper-case before joining them.
Java 8: From List to upper-case String comma separated
If you want to find out more about stream, I strongly suggest this cool video of Venkat Subramaniam.
Let’s play
The best way to learn it’s playing! Copy this class with all the implementations discussed and play with that. There is already a small test for each of them 🙂