Join collection As Comma Delimited String - Java java.util

Java examples for java.util:Collection Join

Description

Join collection As Comma Delimited String

Demo Code


//package com.java2s;

import java.util.Arrays;
import java.util.Collection;

import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        String[] col = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(collectionAsCommaDelimitedString(col));
    }//from  ww  w . ja  v  a 2s . c o m

    public static String collectionAsCommaDelimitedString(String[] col) {
        if (col == null || col.length == 0) {
            return "";
        }
        return collectionAsCommaDelimitedString(Arrays.asList(col));
    }

    public static String collectionAsCommaDelimitedString(Collection<?> col) {
        if (col == null || col.isEmpty()) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        Iterator<?> it = col.iterator();
        while (it.hasNext()) {
            sb.append(it.next().toString());
            if (it.hasNext()) {
                sb.append(",");
            }
        }

        return sb.toString();
    }
}

Related Tutorials