Java Collection Join join(final String delimiter, final Collection elements)

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

Description

Same as #join(String,Object) but with a java.util.Collection instead of an Array for the elements.

License

Apache License

Declaration

public static String join(final String delimiter, final Collection<?> elements) 

Method Source Code


//package com.java2s;
/*/*from   ww  w .ja va 2 s .c  o  m*/
 * Copyright 2012 Daniel Bechler
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.*;

public class Main {
    /**
     * Joins all non-null elements of the given <code>elements</code> into one String.
     *
     * @param delimiter Inserted as separator between consecutive elements.
     * @param elements  The elements to join.
     *
     * @return A long string containing all non-null elements.
     */
    public static String join(final String delimiter, final Object... elements) {
        final StringBuilder sb = new StringBuilder();
        for (final Object part : elements) {
            if (part == null) {
                continue;
            }
            if (sb.length() > 0) {
                sb.append(delimiter);
            }
            sb.append(part.toString());
        }
        return sb.toString();
    }

    /**
     * Same as {@link #join(String, Object...)} but with a {@link java.util.Collection} instead of an Array
     * for the elements.
     *
     * @see #join(String, java.util.Collection)
     */
    public static String join(final String delimiter, final Collection<?> elements) {
        if (elements == null || elements.isEmpty()) {
            return "";
        }
        return join(delimiter, elements.toArray(new Object[elements.size()]));
    }

    public static boolean isEmpty(final String s) {
        return !hasText(s);
    }

    public static boolean hasText(final String s) {
        return s != null && s.trim().length() > 0;
    }
}

Related

  1. join(final Collection collection)
  2. join(final Collection collection, final String delimiter)
  3. join(final Collection objs, final String delimiter)
  4. join(final Collection objs, String delimiter)
  5. join(final String d, final Collection c)
  6. join(final String s, final Collection c)
  7. join(final String sep, final Collection c)
  8. join(final String sep, final Collection strs)
  9. join(final String separator, final Collection objects)