array To Formatted Comma Separated String - Java Collection Framework

Java examples for Collection Framework:Array Join

Description

array To Formatted Comma Separated String

Demo Code


import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

public class Main{
    public static void main(String[] argv) throws Exception{
        Object[] anArray = new String[]{"1","abc","level",null,"java2s.com","asdf 123"};
        System.out.println(arrayToFormattedCommaSeparatedString(anArray));
    }/*  w w w  .  ja v  a 2 s  . c  o m*/
    public static String arrayToFormattedCommaSeparatedString(
            Object[] anArray) {
        StringBuilder result = new StringBuilder();
        int count = 0;

        for (Object value : anArray) {
            if (count > 0) {
                result.append(",");
            }
            if (value instanceof String) {
                result.append("'" + value + "'");
            } else if (value instanceof Long || value instanceof Integer) {
                result.append(value);
            }
            count++;
        }
        return result.toString();
    }
}

Related Tutorials