Searching...
Friday, 25 October 2013

Java List to Comma Separated String Example

10:45
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


0 comments: