Java - Write code to Concatenates the given parts and puts 'glue' between them.

Requirements

Write code to Concatenates the given parts and puts 'glue' between them.

Join elements from a Collection to a string

Hint

Use StringBuilder and for loop

Demo

//package com.book2s;

public class Main {
    /**//from  w  w w  .jav  a2 s .c  om
     * Concatenates the given parts and puts 'glue' between them.
     */
    public static String explode(
            java.util.Collection<? extends Object> parts, String glue) {
        return explode(parts.toArray(new Object[parts.size()]), glue);
    }

    /**
     * Concatenates the given parts and puts 'glue' between them.
     */
    public static String explode(Object[] parts, String glue) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            Object next = parts[i];
            sb.append(next.toString());
            if (i < parts.length - 1) {
                sb.append(glue);
            }
        }
        return sb.toString();
    }
}

Related Exercise