Java Collection Join join(Collection c, String separator)

Here you can find the source of join(Collection c, String separator)

Description

Join operation on a collection

License

Open Source License

Parameter

Parameter Description
c a collection
separator of the collection elements

Declaration

public static String join(Collection<?> c, String separator) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Collection;

public class Main {
    /**// w  ww. jav  a  2 s . c om
     * Join operation on a collection
     * 
     * @param c a collection
     * @param separator of the collection elements
     * @return 
     */
    public static String join(Collection<?> c, String separator) {
        if (!isSet(separator)) {
            throw new IllegalArgumentException("Separator is null or empty");
        }

        if (c == null || c.size() == 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder();

        for (Object element : c) {
            String elementValue = (element == null) ? "" : element.toString();
            sb.append(elementValue).append(separator);
        }

        // remove latest separator
        sb.setLength(sb.length() - separator.length());

        return sb.toString();
    }

    /**
     * Checks if a string is neither empty ("") nor <code>null</code>.
     *
     * @param  s   the string to check, may be <code>null</code>.
     *
     * @return <code>true</code> if the string is neither empty ("")
     *         nor <code>null</code>.
     */
    public static boolean isSet(String s) {
        return ((s != null) && (s.length() != 0));
    }
}

Related

  1. join(Collection strings, String separator)
  2. join(Collection strs, String separator)
  3. join(Collection c, String delim)
  4. join(Collection c, String delimiter)
  5. join(Collection c, String insert)
  6. join(Collection col, String delim)
  7. join(Collection col, String separator)
  8. join(Collection coll, String delim)
  9. join(Collection collection, String delimiter)