Best way to convert list to comma separated string in java

Best way to convert list to comma separated string in java

To convert a list of elements to a comma-separated string in Java, you can use the String.join() method, which was introduced in Java 8. This method allows you to join elements from a collection with a specified delimiter. Here's how you can use it:

import java.util.ArrayList; import java.util.List; import java.util.StringJoiner; public class ListToCommaSeparatedString { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); // Using String.join() method String commaSeparatedString = String.join(", ", list); System.out.println(commaSeparatedString); } } 

Output:

apple, banana, cherry 

In the example above, we first create a List<String> called list containing three elements. Then, we use String.join(", ", list) to concatenate the elements with a comma and a space as the delimiter, resulting in a comma-separated string.

This approach is concise and effective for converting a list to a comma-separated string in Java 8 and later. If you're using an earlier version of Java, you can use a loop to manually concatenate the elements with the desired delimiter.


More Tags

delta-lake ioc-container contain angular-ng-class catmull-rom-curve django-admin-actions google-analytics purrr kql security

More Java Questions

More Electrochemistry Calculators

More Mixtures and solutions Calculators

More Math Calculators

More Financial Calculators