Java CSV String Create getCSV(Collection values)

Here you can find the source of getCSV(Collection values)

Description

get CSV string from the collections.

License

Open Source License

Parameter

Parameter Description
values Collection

Return

StringBuffer

Declaration

public static String getCSV(Collection<?> values) 

Method Source Code


//package com.java2s;

import java.util.Collection;
import java.util.Iterator;

public class Main {
    public static final String CSV_SEPARATOR = ",";

    /**/*from  w w  w .  j  a  va 2  s .c o m*/
     * get CSV string from the collections. use comma as separator. blank items
     * will be skipped.
     * 
     * @param values Collection
     * @return StringBuffer
     */
    public static String getCSV(Collection<?> values) {
        return getCSV(values, CSV_SEPARATOR, true);
    }

    public static String getCSV(Collection<?> values, boolean warpSingleQutoa) {
        return getCSV(values, CSV_SEPARATOR, true, warpSingleQutoa).toString();
    }

    /**
     * convert the collection into CSV.
     * 
     * @param values
     * @param separators
     * @param ignoreBlank if true blank entries will be skipped
     * 
     * @return StringBuffer
     */
    public static String getCSV(Collection<?> values, String separators, boolean ignoreBlank) {
        return getCSV(values, separators, ignoreBlank, false).toString();
    }

    private static StringBuffer getCSV(Collection<?> values, String separators, boolean ignoreBlank,
            boolean warpSingleQutoa) {
        StringBuffer sb = new StringBuffer();
        if (values == null || values.size() == 0) {
            return sb;
        }

        for (Iterator<?> it = values.iterator(); it.hasNext();) {
            String value = it.next().toString();
            if (ignoreBlank && isBlank(value)) {
                continue;
            }

            if (sb.length() > 0) {
                sb.append(separators);
            }
            sb.append(warpSingleQutoa ? addSingleQuote(value) : value);
        }

        return sb;
    }

    public static boolean isBlank(Object str) {
        return str == null || str.toString().trim().length() == 0;
    }

    private static String addSingleQuote(String strSource) {
        if (strSource == null) {
            strSource = "";
        }
        return "'" + strSource + "'";
    }

    public static String trim(String str) {
        return str == null ? null : str.trim();
    }
}

Related

  1. csv(String separator, String... elements)
  2. getCSV(Collection coll)
  3. getCsv(Collection collection)
  4. getCSVPhrase(Collection objects)
  5. toCSV(int[] a)
  6. toCsv(Object[] arr, String format)