Java - Write code to Join the elements of the given array to a string, separated by the given separator string.

Requirements

Write code to Join the elements of the given array to a string, separated by the given separator string.

Demo

//package com.book2s;
import java.util.Arrays;
import java.util.Iterator;

public class Main {
    /**//from w  w  w . ja  va  2s  .com
     * Joins the elements of the given array to a string, separated by the given separator string.
     *
     * @param array the array to join
     * @param separator the separator string
     *
     * @return a string made up of the string representations of the given array's members, separated by the given separator
     *         string
     */
    public static String join(Object[] array, String separator) {
        return array != null ? join(Arrays.asList(array), separator) : null;
    }

    /**
     * Joins the elements of the given iterable to a string, separated by the given separator string.
     *
     * @param iterable the iterable to join
     * @param separator the separator string
     *
     * @return a string made up of the string representations of the given iterable members, separated by the given separator
     *         string
     */
    public static String join(Iterable<?> iterable, String separator) {
        if (iterable == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;

        for (Object object : iterable) {
            if (!isFirst) {
                sb.append(separator);
            } else {
                isFirst = false;
            }

            sb.append(object);
        }

        return sb.toString();
    }

    /**
     * Joins the elements of the given iterator to a string, separated by the given separator string.
     *
     * @param iterator the iterator to join
     * @param separator the separator string
     *
     * @return a string made up of the string representations of the given iterator members, separated by the given separator
     *         string
     */
    public static String join(Iterator<?> iterator, String separator) {
        if (iterator == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;

        while (iterator.hasNext()) {
            if (!isFirst) {
                sb.append(separator);
            } else {
                isFirst = false;
            }

            sb.append(iterator.next());
        }

        return sb.toString();
    }
}

Related Exercise