Join an Iterable of String into one string with a separator - Java java.lang

Java examples for java.lang:String Join

Description

Join an Iterable of String into one string with a separator

Demo Code


//package com.java2s;
import java.util.Iterator;

public class Main {
    /**/*from  w ww .j a  v  a2  s .com*/
     * Join an Iterable of String into one string with a separator
     * @param source
     * @param separator
     */
    public static String join(Iterable<String> source, String separator) {
        Iterator<String> iterator = source.iterator();
        if (source == null || !iterator.hasNext()) {
            return "";
        }
        StringBuilder builder = new StringBuilder(iterator.next());
        while (iterator.hasNext()) {
            builder.append(separator).append(iterator.next());
        }
        return builder.toString();
    }
}

Related Tutorials