How to Convert List to Csv String in Java


In this example we will show how to convert a list to a csv string in Java.

Source Code

package com.beginner.examples;

import java.util.ArrayList;
import java.util.List;

public class ConvertListToCsvString {

	public static void main(String[] args) {
		
		//Create String list object.
		List list = new ArrayList();
		list.add("Alice");
		list.add("Bob");
		list.add("Jack");
		
		/*
		 * Use StringBuilder to adding String.
		 */
		StringBuilder stringBuilder = new StringBuilder();
		for(String str : list) {
			if(stringBuilder.length() !=0) {
				stringBuilder.append(",");
			}
			stringBuilder.append(str);
		}
		System.out.println(stringBuilder.toString());
	}

}

Output:

Alice,Bob,Jack

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments