Java Collection Join join(Collection c, String insert)

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

Description

Return the string created by inserting insert between the members of c .

License

Open Source License

Declaration

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

Method Source Code


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

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

public class Main {
    /**//from w w  w .ja v  a  2s  .c  o  m
     * Return the string created by inserting {@code insert} between
     * the members of {@code c}.
     *
     * @doc.test Note that non-string types are converted to Strings:
     * js> ListUtils.join(Tools.l(1), " + ")
     * 1.0
     * js> ListUtils.join(Tools.l(1, 2), " + ")
     * 1.0 + 2.0
     * js> ListUtils.join(Tools.l(1, 2, 3), " + ")
     * 1.0 + 2.0 + 3.0
     */
    public static String join(Collection<?> c, String insert) {
        return join(c, insert, insert);
    }

    /**
     * Return the string created by inserting {@code insert} between
     * the members of {@code c}, and {@code preFinal} before the last one.
     *
     * @doc.test
     * js> ListUtils.join(Tools.l("apples"), ", ", " or ")
     * apples
     * js> ListUtils.join(Tools.l("apples", "oranges"), ", ", " or ")
     * apples or oranges
     * js> ListUtils.join(Tools.l("apples", "oranges", "pears"), ", ", " or ")
     * apples, oranges or pears
     * @doc.test Non-string types are converted to strings:
     * js> ListUtils.join(Tools.l(1, 2, 3), " + ", " - ")
     * 1.0 + 2.0 - 3.0
     */
    public static String join(Collection<?> c, String insert, String preFinal) {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Iterator<?> it = c.iterator(); it.hasNext(); first = false) {
            String s = it.next().toString();
            if (!first) {
                result.append(it.hasNext() ? insert : preFinal);
            }
            result.append(s);
        }
        return result.toString();
    }
}

Related

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