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

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts