Java String Join join(String delimiter, Object... parts)

Here you can find the source of join(String delimiter, Object... parts)

Description

join

License

Open Source License

Declaration

public static String join(String delimiter, Object... parts) 

Method Source Code

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

import java.util.*;

public class Main {
    public static String join(String delimiter, Object... parts) {
        return join(Arrays.asList(parts), delimiter);
    }/*from www .j  a  v a 2s  .c  o  m*/

    public static String join(Object[] parts, String delimiter) {
        return join(Arrays.asList(parts), delimiter);
    }

    /**
     * Joins the String values of the contents of the Object array (parts) by inserting (delimiter) between each String.
     * This is the counterpart to String.split() and does the exact opposite of String.split().
     * @param parts The Object array that contains the objects, the String values of which you want to join together.
     * @param delimiter The String to insert between each object's String value in (parts)
     * @return Returns a String object constructed by joining each String value of the objects in (parts) using
     *  String.valueOf() on each object and with the given (delimiter). Returns null if the (parts) array is null
     *  or returns the empty String if the (parts) array is empty. A null delimiter throws a NullPointerException.
     * @author: David Kovacs
     */
    public static String join(Iterable<?> parts, String delimiter) {
        if (parts == null)
            return null;
        if (delimiter == null)
            throw new NullPointerException(
                    "The delimiter cannnot be null. Use an empty string if you want no delimiter.");

        StringBuilder result = new StringBuilder();
        String currentDelim = null;
        for (Object part : parts) {
            if (currentDelim == null)
                currentDelim = delimiter;
            else
                result.append(currentDelim);
            result.append(String.valueOf(part));
        }
        return result.toString();
    }

    /** This works the same as {@link String#valueOf(Object)}, except it returns an empty string instead of "null" if the input is null. */
    public static String valueOf(Object o) {
        return o == null ? "" : String.valueOf(o);
    }
}

Related

  1. join(String delimiter, Collection items)
  2. join(String delimiter, Iterable elements)
  3. join(String delimiter, Iterable strings)
  4. join(String delimiter, Iterable strings)
  5. join(String delimiter, Object... objects)
  6. join(String delimiter, String... items)
  7. join(String delimiter, String... params)
  8. join(String delimiter, String... strings)
  9. join(String delimiter, T... array)