Returns a csv string of the given values. - Java java.io

Java examples for java.io:File CSV

Description

Returns a csv string of the given values.

Demo Code

/**/*from  w  ww. j  av  a 2  s .  c o m*/
 * Helpful methods for collections.
 * 
 * ## Legal stuff
 * 
 * Copyright 2014-2014 Ekkart Kleinod <ekleinod@edgesoft.de>
 * 
 * This file is part of edgeUtils.
 * 
 * edgeUtils is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * edgeUtils is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with edgeUtils.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @author Ekkart Kleinod
 * @version 0.2
 * @since 0.2
 */
//package com.java2s;

import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection theCollection = java.util.Arrays.asList("asdf",
                "java2s.com");
        String theSeparator = "java2s.com";
        System.out.println(toCSVString(theCollection, theSeparator));
    }

    /**
     * Returns a csv string of the given values.
     * 
     * @param theCollection collection to stringify
     * @param theSeparator separator string
     * @return csv string
     *    @retval empty if collection is empty or any parameter is null
     * 
     * @version 0.2
     * @since 0.2
     */
    public static <T> String toCSVString(Collection<T> theCollection,
            String theSeparator) {

        if ((theCollection == null) || (theSeparator == null)) {
            return "";
        }

        StringBuffer sbReturn = new StringBuffer();

        boolean isFurther = false;
        for (T theElement : theCollection) {
            if (isFurther) {
                sbReturn.append(theSeparator);
            }
            if (theElement == null) {
                sbReturn.append(theElement);
            } else {
                sbReturn.append(theElement.toString().trim());
            }
            isFurther = true;
        }

        return sbReturn.toString();
    }
}

Related Tutorials