How to Convert a List to Comma-Separated String in Java
Table of Contents
Lists in Java are a collection of items that can be held in a single variable.
If this list is holding strings inside, you have the option to convert it to a comma-separated string.
In this post, we'll learn the two best ways to turn a string list into a comma-separated string in Java.
Using the join() method
The most straight-forward way to convert a string list to a comma-separated string is to use the join()
method that exists on the String
class.
Simply call the join()
method on the list and pass in the separator you want to use.
JAVAList<String> fruits = List.of("apple", "banana", "orange");
String fruitList = String.join(", ", fruits);
System.out.println(fruitList);
BASHapple, banana, orange
Using Java Streams
Another way you can convert a string list to a comma-separated string is to use the collect()
method on the Stream
class.
Basically the idea is to take the list and turn it into a stream, then join the stream using the separator you want.
JAVAList<String> fruits = List.of("apple", "banana", "orange");
String fruitList = fruits.stream()
.collect(Collectors.joining(", "));
System.out.println(fruitList);
BASHapple, banana, orange
And there you have it, your string list is now a comma-separated string!
Conclusion
In this post, we learned two different methods to convert a list of strings to a single comma-separated string.
Your options are to use the join()
method or the collect()
method on the Stream
class.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor