Description

Joins the elements in an input collection using a given separator.

License

Open Source License

Parameter

Parameter Description
A Key type
collection Input collection
separator Separator

Return

String representation of the input collection

Declaration

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

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 Pablo Pavon-Marino.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * Contributors:/*  w w w  .j a va  2  s . c  om*/
 *     Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1
 *     Pablo Pavon-Marino - from version 0.4.0 onwards
 ******************************************************************************/

import java.util.*;

public class Main {
    /**
     * Joins the elements in an input collection using a given separator.
     *
     * @param <A> Key type
     * @param collection Input collection
     * @param separator Separator
     * @return {@code String} representation of the input {@code collection}
     */
    public static <A> String join(Collection<A> collection, String separator) {
        if (collection.isEmpty())
            return "";

        Iterator<A> it = collection.iterator();
        StringBuilder out = new StringBuilder();
        out.append(it.next());

        while (it.hasNext())
            out.append(separator).append(it.next());

        return out.toString();
    }
}

Related

  1. join(Collection strings, String separator)
  2. join(Collection strs)
  3. join(Collection toJoin, String joinBy)
  4. join(Collection tokens, String d)
  5. join(Collection values)
  6. join(Collection data)
  7. join(Collection c, String separator)
  8. join(Collection args, String delimeter)
  9. join(Collection c)