Java Collection Join join(Collection collection, String delimiter)

Here you can find the source of join(Collection collection, String delimiter)

Description

Joins a Collection of typed objects using their toString method, separated by delimiter

License

Apache License

Parameter

Parameter Description
collection Collection of objects
delimiter (optional) String to separate the items of the collection in the joined string - <code>null</code> is interpreted as empty string

Return

the joined string

Declaration

public static String join(Collection<?> collection, String delimiter) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    private final static String EMPTY_STRING = "";

    /**/*from w w  w.ja  v  a2 s .c  o m*/
     * Joins a Collection of typed objects using their toString method, separated by delimiter
     *
     * @param collection Collection of objects
     * @param delimiter  (optional) String to separate the items of the collection in the joined string - <code>null</code> is interpreted as empty string
     * @return the joined string
     */
    public static String join(Collection<?> collection, String delimiter) {

        if (collection == null || collection.isEmpty()) {
            return EMPTY_STRING;
        } else if (delimiter == null) {
            delimiter = EMPTY_STRING;
        }

        StringBuilder builder = new StringBuilder();
        Iterator<?> it = collection.iterator();

        while (it.hasNext()) {
            builder.append(it.next()).append(delimiter);
        }

        int length = builder.length();
        builder.delete(length - delimiter.length(), length);
        return builder.toString();
    }
}

Related

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