Java - Write code to join Iterable<String> to a string using while loop

Requirements

Write code to join

Demo

//package com.book2s;

import java.util.Arrays;
import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        String[] items = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        String separator = "book2s.com";
        System.out.println(join(items, separator));
    }/*  www . java 2s  . c  o m*/

    public static String join(String[] items, String separator) {
        return join(Arrays.asList(items), separator);
    }

    public static String join(Iterable<String> items, String separator) {
        final StringBuilder builder = new StringBuilder();
        final Iterator<String> it = items.iterator();
        while (it.hasNext()) {
            builder.append(it.next());
            if (it.hasNext()) {
                builder.append(separator);
            }
        }
        return builder.toString();
    }

    public static String toString(Object object) {
        if (object == null) {
            return "null";
        }
        return object.toString();
    }

    public static String toString(Iterable<?> it, String separator) {
        final StringBuilder builder = new StringBuilder();
        final Iterator<?> iterator = it.iterator();
        while (iterator.hasNext()) {
            builder.append(iterator.next().toString());
            if (iterator.hasNext()) {
                builder.append(separator);
            }
        }
        return builder.toString();
    }
}

Related Example