Java Array Join join(String[] array, String separator)

Here you can find the source of join(String[] array, String separator)

Description

Joins elements from a given array into a String .

License

Open Source License

Parameter

Parameter Description
array Input array
separator Entry separator

Return

A String

Declaration

public static String join(String[] array, 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://ww  w. j a v  a2 s  . c  o  m
 *     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.Collection;
import java.util.Iterator;

public class Main {
    /**
     * Joins elements from a given array into a {@code String}.
     *
     * @param array Input array
     * @param separator Entry separator
     * @return A String
     * 
     */
    public static String join(String[] array, String separator) {
        if (array.length == 0)
            return "";

        StringBuilder out = new StringBuilder();
        out.append(array[0]);

        for (int i = 1; i < array.length; i++)
            out.append(separator).append(array[i]);

        return out.toString();
    }

    /**
     * Joins elements from a given collection into a {@code String}.
     *
     * @param collection Input collection
     * @param separator Entry separator
     * @return A String
     * 
     */
    public static String join(Collection<String> collection, String separator) {
        if (collection.isEmpty())
            return "";

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

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

        return out.toString();
    }
}

Related

  1. join(String[] array, String delimiter)
  2. join(String[] array, String delimiter)
  3. join(String[] array, String sep)
  4. join(String[] array, String separator)
  5. join(String[] array, String separator)
  6. join(String[] arrayOfString)
  7. join(String[] datalines)
  8. join(String[] elements, String separator)
  9. join(String[] elements, String separator)