Get a comma separated list (sorted) from a collection of strings. - Java java.lang

Java examples for java.lang:String Split

Description

Get a comma separated list (sorted) from a collection of strings.

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class Main {
    public static void main(String[] argv) throws Exception {
        Collection arr = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(GetCommaList(arr));
    }/*w ww .j a  v  a2  s.  com*/

    /** 
     * Get a comma separated list (sorted) from a collection of strings.
     * 
     * @param arr Array of Strings
     * @return Comma separated list
     */
    public static String GetCommaList(Collection<String> arr) {
        if ((arr == null) || (arr.size() <= 0))
            return "";
        return GetCommaList(arr, true);
    }

    /** 
     * Get a comma separated list from a collection of strings.
     * 
     * @param arr Array of Strings
     * @param doSort option to sort
     * @return Comma separated list
     */
    public static String GetCommaList(Collection<String> arr, boolean doSort) {
        ArrayList<String> list = new ArrayList<String>(arr);

        StringBuffer buf = new StringBuffer();
        Collections.sort(list);
        for (String str : list) {
            if (buf.length() > 0)
                buf.append(", ");
            buf.append(str);
        }
        return buf.toString();
    }

    /** 
     * Get a comma separated list from an array of strings.
     * 
     * @param args Array of Strings
     * @return Comma separated list
     */
    public static String GetCommaList(String[] args) {
        if (args == null)
            return "";
        return GetCommaList(Arrays.asList(args));
    }
}

Related Tutorials