Java Collection Join join(Collection collection, String separator)

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

Description

join

License

Open Source License

Declaration

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

Method Source Code


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

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

public class Main {
    public static String join(Collection<?> collection, String separator) {

        // handle null, zero and one elements before building a buffer
        if (collection == null) {
            return null;
        }//  ww w  .ja v a2 s .co  m
        Iterator<?> it = collection.iterator();
        if (!it.hasNext()) {
            return "";
        }
        Object first = it.next();
        if (!it.hasNext()) {
            return first instanceof String ? (String) first : first != null ? first.toString() : "";
        }

        // two or more elements
        StringBuilder sbResult = new StringBuilder(256);
        if (first != null) {
            sbResult.append(first);
        }

        while (it.hasNext()) {
            if (separator != null) {
                sbResult.append(separator);
            }
            Object obj = it.next();
            if (obj != null) {
                sbResult.append(obj);
            }
        }
        return sbResult.toString();
    }
}

Related

  1. join(Collection collection, String inputSeparator)
  2. join(Collection collection, String join)
  3. join(Collection collection, String sep)
  4. join(Collection collection, String separator)
  5. join(Collection collection, String separator)
  6. join(Collection collection, String separator)
  7. join(Collection collection, String separatorString)
  8. join(Collection elements, String separator)
  9. join(Collection items, char separator)