In this article, we will understand how to convert a list of string to comma separated string. A list is an ordered collection that allows us to store and access elements sequentially. It contains the index-based methods to insert, update, delete and search the elements. It can also have the duplicate elements.
Below is a demonstration of the same −
Suppose our input is −
Input list: [Java, Scala, Python]
The desired output would be −
The list with comma separated elements: Java, Scala, Python
Algorithm
Step 1 - START Step 2 - Declare a List namely input_list. Step 3 - Define the values. Step 4 - Use the built in function .join() to add comma in between the elements of the object. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.*; public class Demo { public static void main(String args[]){ List<String> input_list = new ArrayList<>( Arrays .asList("Java", "Scala", "Python")); System.out.println("The input_list is defined as: " + input_list); String string = String.join(", ", input_list); System.out.println("The list with comma separated elements: " + string); } }
Output
The input_list is defined as: [Java, Scala, Python] The list with comma separated elements: Java, Scala, Python
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.*; public class Demo { static void add_comma(List<String> input_list){ String string = String.join(", ", input_list); System.out.println("The list with comma separated elements: " + string); } public static void main(String args[]){ List<String> input_list = new ArrayList<>( Arrays .asList("Java", "Scala", "Python")); System.out.println("The list is defined as: " + input_list); add_comma(input_list); } }
Output
The list is defined as: [Java, Scala, Python] The list with comma separated elements: Java, Scala, Python