Java Iterable Join join(CharSequence delimiter, Iterable tokens)

Here you can find the source of join(CharSequence delimiter, Iterable tokens)

Description

join

License

Apache License

Declaration

public static String join(CharSequence delimiter, Iterable tokens) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.List;

public class Main {
    /** default join separator **/
    public static final String DEFAULT_JOIN_SEPARATOR = ",";

    /**//ww w  . j  ava2  s .com
     * join list to string, separator is ","
     * 
     * <pre>
     * join(null)      =   "";
     * join({})        =   "";
     * join({a,b})     =   "a,b";
     * </pre>
     * 
     * @param list
     * @return join list to string, separator is ",". if list is empty, return ""
     */
    public static String join(List<String> list) {
        return join(list, DEFAULT_JOIN_SEPARATOR);
    }

    /**
     * join list to string
     * 
     * <pre>
     * join(null, '#')     =   "";
     * join({}, '#')       =   "";
     * join({a,b,c}, ' ')  =   "abc";
     * join({a,b,c}, '#')  =   "a#b#c";
     * </pre>
     * 
     * @param list
     * @param separator
     * @return join list to string. if list is empty, return ""
     */
    public static String join(List<String> list, char separator) {
        return join(list, new String(new char[] { separator }));
    }

    /**
     * join list to string. if separator is null, use {@link #DEFAULT_JOIN_SEPARATOR}
     * 
     * <pre>
     * join(null, "#")     =   "";
     * join({}, "#$")      =   "";
     * join({a,b,c}, null) =   "a,b,c";
     * join({a,b,c}, "")   =   "abc";
     * join({a,b,c}, "#")  =   "a#b#c";
     * join({a,b,c}, "#$") =   "a#$b#$c";
     * </pre>
     * 
     * @param list
     * @param separator
     * @return join list to string with separator. if list is empty, return ""
     */
    public static String join(List<String> list, String separator) {
        StringBuilder sb = new StringBuilder();
        boolean firstTime = true;
        for (Object token : list) {
            if (firstTime) {
                firstTime = false;
            } else {
                sb.append(separator);
            }
            sb.append(token);
        }
        return sb.toString();
    }

    public static String join(CharSequence delimiter, Iterable tokens) {
        StringBuilder sb = new StringBuilder();
        boolean firstTime = true;
        for (Object token : tokens) {
            if (firstTime) {
                firstTime = false;
            } else {
                sb.append(delimiter);
            }
            sb.append(token);
        }
        return sb.toString();
    }
}

Related

  1. join(CharSequence delimiter, Iterable tokens)
  2. join(CharSequence delimiter, Iterable elements)
  3. join(CharSequence separator, Iterable strings)
  4. join(final CharSequence sep, final Iterable src)