Java Collection Join join(Collection c, String left, String right, String separator)

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

Description

Return a String object join all String object in param c, and add param left and param right to every String object on the left side and right side, separaing with param separator.

License

Apache License

Exception

Parameter Description
ClassCastException if the object in the Collection isnot a String object.

Declaration

public static String join(Collection c, String left, String right, String separator) 

Method Source Code

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

import java.util.*;

public class Main {
    /**/*from ww  w  .ja v  a  2s.  c o m*/
     * Return a String object join all String object in param c, and add
     * param left and param right to every String object on the left side
     * and right side, separaing with param separator.
     *
     * <pre>
     * join(["s1", "s2"], "left", "right", ",") = "lefts1right,lefts2right"
     * </pre>
     *
     * @throws ClassCastException
     *             if the object in the Collection is
     *             not a String object.
     */
    public static String join(Collection c, String left, String right, String separator) {

        if (c == null || c.size() == 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        boolean firstFlag = true;
        for (Iterator it = c.iterator(); it.hasNext();) {
            if (firstFlag) {
                firstFlag = false;
            } else if (separator != null) {
                sb.append(separator);
            }
            String s = (String) it.next();
            if (left != null) {
                sb.append(left);
            }
            sb.append(s);
            if (right != null) {
                sb.append(right);
            }
        }
        return sb.toString();
    }

    public static String join(Collection c) {
        return join(c, "<", ">", ",");
    }
}

Related

  1. join(CharSequence p, Collection collection)
  2. join(CharSequence separator, Collection col)
  3. join(Collection c)
  4. join(Collection c, String d)
  5. join(Collection c, String delim)
  6. join(Collection c, String separator)
  7. join(Collection col, char sep)
  8. join(Collection coll, String separator)
  9. join(Collection collection)