Java Array Join join(String delimiter, String[] elements)

Here you can find the source of join(String delimiter, String[] elements)

Description

Join an array of String elements into a single String.

License

BSD License

Parameter

Parameter Description
delimiter Delimiter to be placed between each element.
elements Array of String elements.

Return

A joined string of all elements separated by the delimiter.

Declaration

public static String join(String delimiter, String[] elements) 

Method Source Code


//package com.java2s;
/*/*from   w  w w  . j  a  va 2s . c o  m*/
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */

import java.util.*;

public class Main {
    /**
     * Join an array of String elements into a single String.
     *
     * @param delimiter Delimiter to be placed between each element.
     * @param elements  Array of String elements.
     * @return A joined string of all elements separated by the delimiter.
     */
    public static String join(String delimiter, String[] elements) {
        StringBuilder ret = new StringBuilder();
        boolean firstIteration = true;
        for (String s : elements) {
            if (!firstIteration) {
                ret.append(delimiter);
            } else {
                firstIteration = false;
            }
            ret.append(s);
        }
        return ret.toString();
    }

    /**
     * Join a list of String elements into a single String.
     *
     * @param delimiter Delimiter to be placed between each element.
     * @param elements  List of String elements.
     * @param <T>       Type of element in the list.
     * @return A joined string of all elements separated by the delimiter.
     */
    public static <T> String join(String delimiter, List<T> elements) {
        StringBuilder ret = new StringBuilder();
        Iterator<T> it = elements.iterator();
        while (it.hasNext()) {
            ret.append(it.next().toString());
            if (it.hasNext()) {
                ret.append(delimiter);
            }
        }
        return ret.toString();
    }
}

Related

  1. join(Object[] values, String join)
  2. join(Object[]... arrays)
  3. join(String delimiter, Object[] strings)
  4. join(String delimiter, short[] array)
  5. join(String delimiter, String[] array)
  6. join(String delimiter, String[] s)
  7. join(String glue, String[] strings)
  8. join(String glue, String[] strings)
  9. join(String s, String[] arr, int off, int end)