- How to Convert a List of String to Comma Separated String (CSV) in Java 8? Example
- 1. List of String to Comma Separated String in Java
- Important points
- Convert a Set of String to a comma separated String in Java
- Example 1: Using String.join() method
- Example 2: Using Stream API
- Top Related Articles:
- About the Author
- Java HashSet to Comma Separated String Example
- How to convert HashSet to comma separated String in Java?
- 1. Using the join method of the String class (Java 8 and later versions)
- 2. Using Apache Commons
- 3. Using the toString method
- 4. Using the Iterator and StringBuilder
- About the author
- Convert a Set of String to a comma separated String in Java
- Convert a Set of String to a comma separated String in Java
- #Comma Separated #String to #List in Java
- Enclose each string in a comma separated string in double quotes
- Convert String into comma separated List in Java
- Recommended: Please try your approach on first, before moving on to the solution.
How to Convert a List of String to Comma Separated String (CSV) in Java 8? Example
Before Java 8, it was not straightforward to convert a list of String to a comma-separated String. You have to loop through the collection or list and join them manually using String concatenation, which can take up more than 4 lines of code. Of course, you could encapsulate that into your own utility method and you should but JDK didn’t provide anything useful for such a common operation. Btw, things have changed. From Java 8 onwards you can do this easily. JDK 8 has provided a utility class called StringJoiner as well as added a join() method into String class to convert a List , Set , Collection, or even array of String objects to a comma-separated String in Java.
This method accepts a delimiter and an Iterable which contains String. Since all Collection classes implement Iterable, it’s possible to join all String from a List or Set using a delimiter like a comma, colon, or even space.
Btw, like most things, you need to know some small details. For example, if your List or Set contains null then a «null» string will be added into the final String, so please beware of that. If you don’t want null , it’s better to remove any nulls before joining strings from the list.
By the way, Java 8 is full of such excellent features which are often get ignored in the limelight of lambda expression, Stream API, new Date Time API, and other significant features.
1. List of String to Comma Separated String in Java
Here is an example of converting a list and set to a comma-separated String in Java 8:
package tool; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * A simple Java Program to to remove duplicates from Stream in Java 8 * This example uses Stream.distinct() method to remove * duplicates. */ public class Hello public static void main(String args[]) ListString> books = Arrays.asList("Effective Java", "Clean Code", "Java Concurrency in Practice"); System.out.println(books); String bookString = String.join(",", books); System.out.println(bookString); SetString> authors = new HashSet>(Arrays.asList("Josh Bloch", "Uncle Bob Martin", "Brian Goetz")); System.out.println(authors); String authorString = String.join(",", books); System.out.println(authorString); > > Output [Effective Java, Clean Code, Java Concurrency in Practice] Effective Java,Clean Code,Java Concurrency in Practice [Josh Bloch, Uncle Bob Martin, Brian Goetz] Effective Java,Clean Code,Java Concurrency in Practice
You can see that if you directly print the list or set, all the elements are written inside a bracket. Since we just need a CSV or comma-separated String, we need to use the String.join() method, and that’s what we have done in this example.
String bookString = String.join(",", books);
String authorString = String.join(",", books);
Are the two lines which are doing all the work of joining all String from the list and set into one separated by a comma. If you want, you can change the delimiter to colon or space to create a different String based upon your requirement.
By the way, Java 8 is full of such hidden features which are often get ignored in the limelight of lambda expression, Stream API, and other major features. If you are interested to learn more about new Java 8 features, I suggest you go through What’s New in Java 8 on Udemy, one of the comprehensive courses to learn Java.
Important points
1. The String.join() method is only available from JDK 8 onwards. So, if you need to convert a list or set to a delimited String in an earlier version, you can loop through all the elements and join them manually using a StringBuffer or StringBuilder .
2. A «null» as String will be added to your output if your list or set contains a null element.
3. Since String.join() method accepts an Iterable, you can pass any Collection implementation to it, e.g. List, Set, ArrayList , LinkedList, Vector, HashSet, TreeSet, LinkedHashSet, etc.
4. The String.join() is a static method, so you don’t need a String object to call this one.
That’s all about how to convert a list of String to a comma-separated String in Java. There are many ways to complete this task, but as I said, prefer String.join() if you are using Java 8 or higher version. You can also change the delimiter to any character or String you want. For example, if your String is separated by a colon instead of a comma, then you can just use a colon, and it will work like this. Just beware of null though.
Convert a Set of String to a comma separated String in Java
Problem description: We have given a Set that contains String elements. Our task is to convert this set of string to a comma separated string in Java.
For example:
Input: Set = ["Apple", "Orange", "Mango"] Output: "Apple, Orange, Mango" Input: Set = ["J", "a", "v", "a"] Output: "J, a, v, a"
Example 1: Using String.join() method
We can do this conversion using join() method of String class. The string join() method returns a string by combining all the elements of an iterable collection(list, set etc), separated by the given separator.
Here we will pass the set to the String join() method and separator as comma (,). This will join all the set elements with the comma and return a comma separated string.
import java.util.*; public class JavaExample < public static void main(String args[]) < // Set of Strings SetanimalSet = new HashSet<>(); animalSet.add("Lion"); animalSet.add("Tiger"); animalSet.add("Monkey"); animalSet.add("Rabbit"); // Displaying Set elements System.out.println("Set of Strings: " + animalSet); // Convert the Set of Strings to comma separated String String str = String.join(", ", animalSet); // Display the Comma separated String as output System.out.println("Comma Separated String: "+ str); > >
Example 2: Using Stream API
Stream API was introduced in java 8. In the following example, we are using stream API for the conversion.
import java.util.*; import java.util.stream.Collectors; public class JavaExample < public static void main(String args[]) < // Set of Strings SetanimalSet = new HashSet<>(); animalSet.add("Lion"); animalSet.add("Tiger"); animalSet.add("Monkey"); animalSet.add("Rabbit"); // Displaying Set elements System.out.println("Set of Strings: " + animalSet); // Using Stream API for conversion // collect() method returns the result of the // intermediate operations performed on the stream String str = animalSet.stream().collect( Collectors.joining(",")); // Display the Comma separated String as output System.out.println("Comma Separated String: "+ str); > >
Set of Strings: [Monkey, Lion, Rabbit, Tiger] Comma Separated String: Monkey,Lion,Rabbit,Tiger
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Java HashSet to Comma Separated String Example
This example shows how to convert HashSet to a comma separated string in Java. This example also shows how to convert Set to String using various methods.
How to convert HashSet to comma separated String in Java?
There are several ways using which we can convert Set to comma separated string in Java.
1. Using the join method of the String class (Java 8 and later versions)
The join method of the String class can be used for this conversion.
The join method returns a new String object made from the specified elements joined by the specified delimiter. This method is only available from Java version 8. If you are using an older version of Java, the join method is not available and you need to use other approaches given in this example.
2. Using Apache Commons
If you are using the Apache Commons library, you can use the join method of the StringUtils class.
3. Using the toString method
The toString method of the HashSet class returns a string representation of all the elements of the HashSet in “[element 1, element 2,….element n]” format.
If you want to remove the enclosing square brackets and spaces, you can remove them by using below given regular expression along with the String replaceAll method.
4. Using the Iterator and StringBuilder
This approach does not use any built-in methods to convert Set to a comma-separated string. Instead, it uses the Iterator to iterate through HashSet elements and append them to the StringBuilder object one by one.
Note: The StringBuilder class was introduced in Java version 1.5. If you are using Java 1.4 or older version, you can use the StringBuffer class instead.
In addition to these approaches, if you are using Google’s Guava library in your project, you can also use the Joiner class to convert HashSet to comma separated string.
Please let me know your views in the comments section below.
About the author
I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.
Convert a Set of String to a comma separated String in Java
Given a String, the task is to convert it into Comma separated List. Approach: This can be achieved by converting the String into String Array, and then creating an List from that array.
Convert a Set of String to a comma separated String in Java
Given a Set of String, the task is to convert the Set to a comma separated String in Java.
Input: Set = ["Geeks", "ForGeeks", "GeeksForGeeks"] Output: "Geeks, For, Geeks"Input: Set = ["G", "e", "e", "k", "s"] Output: "G, e, e, k, s"
Approach: This can be achieved with the help of join() method of String as follows.
- Get the Set of String.
- Form a comma separated String from the Set of String using join() method by passing comma ‘, ‘ and the set as parameters.
- Print the String.
Below is the implementation of the above approach:
Set of String: [ForGeeks, Geeks, GeeksForGeeks] Comma separated String: ForGeeks, Geeks, GeeksForGeeks
How to split a comma-separated string?, You could do this: String str = «»; List
#Comma Separated #String to #List in Java
#Comma Separated #String to #List in Java ; #Comma Separated ; #String to ; #List in Java. Duration: 7:24
Enclose each string in a comma separated string in double quotes
I am working on a requirement where I need to enclose the individual strings in a comma-separated string in double-quotes while leaving the empty strings.
Eg : The string the,quick,brown. fox,jumped. over,the,lazy,dog should be converted to «the»,»quick»,»brown». «fox»,»jumped». «over»,»the»,»lazy»,»dog»
I have this piece of code that works. But wondering whether there is a better way to do this. btw, I am on JDK 8.
String str = "the,quick,brown. fox,jumped. over,the,lazy,dog"; //split the string List list = Arrays.asList(str.split(",", -1)); // add double quotes around each list item and collect it as a comma separated string String strout = list.stream().collect(Collectors.joining("\",\"", "\"", "\"")); //replace two consecutive double quotes with a empty string strout = strout.replaceAll("\"\"", ""); System.out.println(strout);
You can use split and use stream :
public static String covert(String str) < return Arrays.stream(str.split(",")) .map(s ->s.isEmpty() ? s : '"' + s + '"') .collect(Collectors.joining(",")); >
String str = "the,quick,brown. fox,jumped. over,the,lazy,dog"; System.out.println(covert(str));
"the","quick","brown". "fox","jumped". "over","the","lazy","dog"
How to convert a comma separated String into an ArrayList in Java?, Split the String into an array of Strings using the split() method. · Now, convert the obtained String array to list using the asList() method of
Convert String into comma separated List in Java
Given a String, the task is to convert it into Comma separated List.
Input: String = "Geeks For Geeks" Output: List = [Geeks, For, Geeks]Input: String = "G e e k s" Output: List = [G, e, e, k, s]
Recommended: Please try your approach on first, before moving on to the solution.
Approach: This can be achieved by converting the String into String Array, and then creating an List from that array. However this List can be of 2 types based on their method of creation – modifiable, and unmodifiable.
- Creating an unmodifiable List :