Join collection using coma delimiter - Java java.util

Java examples for java.util:Collection Join

Description

Join collection using coma delimiter

Demo Code


//package com.java2s;
import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        System.out.println(join(collection));
    }/*from www . jav a 2s. c o  m*/

    /**
     * Join collection using coma delimiter
     *
     * @param collection A collection to join
     * @return Joined collection as string
     */
    public static String join(Collection<?> collection) {
        return join(collection, ",");
    }

    /**
     * Join collection using custom delimiter
     *
     * @param collection A collection to join
     * @param delimiter  Custom join delimiter
     * @return Joined collection as string
     */
    public static String join(Collection<?> collection, String delimiter) {
        if (collection == null) {
            return null;
        }
        StringBuilder builder = new StringBuilder();
        for (Object element : collection) {
            if (builder.length() > 0) {
                builder.append(delimiter);
            }
            builder.append(element != null ? element.toString() : "");
        }
        return builder.toString();
    }
}

Related Tutorials