Java String Join join(String delimiter, Iterable elements)

Here you can find the source of join(String delimiter, Iterable elements)

Description

Join a list of elements into a single string with the specified delimiter.

License

Open Source License

Parameter

Parameter Description
delimiter The delimiter to use
elements The elements to join

Return

A new String that is composed of the elements separated by the delimiter

Declaration

public static String join(String delimiter, Iterable<String> elements) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Arrays;

public class Main {
    /**/*  w  ww  .j  a v a  2 s  . c  o  m*/
     * Join a list of elements into a single string with the specified delimiter.
     *
     * @param delimiter The delimiter to use
     * @param elements  The elements to join
     *
     * @return A new String that is composed of the elements separated by the delimiter
     */
    public static String join(String delimiter, Iterable<String> elements) {
        if (delimiter == null) {
            delimiter = "";
        }
        StringBuilder sb = new StringBuilder();
        for (String element : elements) {
            if (!isEmpty(element)) {
                // Add the separator if it isn't the first element
                if (sb.length() > 0) {
                    sb.append(delimiter);
                }
                sb.append(element);
            }
        }

        return sb.toString();
    }

    /**
     * Join a list of elements into a single string with the specified delimiter.
     *
     * @param delimiter The delimiter to use
     * @param elements  The elements to join
     *
     * @return A new String that is composed of the elements separated by the delimiter
     */
    public static String join(String delimiter, String... elements) {
        return join(delimiter, Arrays.asList(elements));
    }

    /**
     * Null-safe method for checking whether a string is empty. Note that the string
     * is trimmed, so this method also considers a string with whitespace as empty.
     *
     * @param str The string to verify
     *
     * @return True if the string is empty, false otherwise
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }
}

Related

  1. join(String connector, Object... objects)
  2. join(String delim, List strings)
  3. join(String delim, Object... objects)
  4. join(String delimiter, Collection objects)
  5. join(String delimiter, Collection items)
  6. join(String delimiter, Iterable strings)
  7. join(String delimiter, Iterable strings)
  8. join(String delimiter, Object... objects)
  9. join(String delimiter, Object... parts)