get Comma Separated String - Android java.lang

Android examples for java.lang:String Split

Description

get Comma Separated String

Demo Code

import java.util.Iterator;

public class Main{
  public static final String EMPTY_STRING = "";
    public static String getCommaSeparatedString(Iterable<String> list) {
        return getCommaSeparatedString(list, false);
    }// ww  w  .ja v  a  2 s  .  c  o m
    public static String getCommaSeparatedString(Iterable<String> list,
            boolean addSpace) {
        String separator = addSpace ? ", " : ",";
        Iterator<String> iterator = list.iterator();
        StringBuilder commaStringBuilder = new StringBuilder(EMPTY_STRING);
        String current = EMPTY_STRING;
        if (iterator.hasNext()) {
            current = iterator.next();
            commaStringBuilder.append(current);
        }

        while (iterator.hasNext()) {
            String nextString = iterator.next();
            if (isNullOrEmpty(current) || isNullOrEmpty(nextString)) {
                commaStringBuilder.append(nextString);
                current = nextString;
            } else {
                commaStringBuilder.append(separator);
                commaStringBuilder.append(nextString);
                current = nextString;
            }
        }
        return commaStringBuilder.toString();
    }

    public static boolean isNullOrEmpty(String string) {
        return (string == null || string.length() == 0);
    }
    public static boolean isNullOrEmpty(CharSequence sequence) {
        return (sequence == null || sequence.length() == 0);
    }
}

Related Tutorials