Java List to Comma Separated String Example

package com.pretech;
import java.util.*;
public class ListToString {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("welcome");
		list.add("to");
		list.add("pretech blog");
		System.out.println(getListAsCommaSeparatedString(list));
	}
	public static String getListAsCommaSeparatedString(List stringList) {
		String result = null;
		boolean firstItem = true;
		if (stringList != null && !stringList.isEmpty()) {
			StringBuffer sb = new StringBuffer();
			for (Iterator i = stringList.iterator(); i.hasNext();) {
				if (firstItem) {
					firstItem = false;
				} else {
					sb.append(",");
				}
				sb.append(i.next().toString().trim());
			}
			result = sb.toString();
		}
		return result;
	}
}

Output



welcome,to,pretech blog


No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts