Java Collection Join join(final String sep, final Collection c)

Here you can find the source of join(final String sep, final Collection c)

Description

Join a bunch of objects into a string delimited by the separator

License

Open Source License

Parameter

Parameter Description
sep a parameter
c a parameter

Declaration

public static String join(final String sep, final Collection<? extends Object> c) 

Method Source Code


//package com.java2s;

import java.util.*;

public class Main {
    /**/*  w w  w. ja v  a  2 s .  c  om*/
     * Join a bunch of objects into a string delimited by the separator
     *
     * @param sep
     * @param c
     * @return
     */
    public static String join(final String sep, final Collection<? extends Object> c) {
        if (c == null) {
            return null;
        }
        if (c.size() == 1) {
            return String.valueOf(c.iterator().next());
        }
        if (c.size() == 0) {
            return "";
        }
        final StringBuilder sb = new StringBuilder();
        String s = "";
        for (final Object o : c) {
            sb.append(s).append(String.valueOf(o));
            s = sep;
        }
        return sb.toString();
    }

    /**
     * Join a bunch of objects into a string delimited by the separator
     *
     * @param sep
     * @param ol
     * @return
     */
    public static String join(final String sep, final Object... ol) {
        if (ol == null || ol.length == 0) {
            return "";
        }
        if (ol.length == 1) {
            return String.valueOf(ol[0]);
        }
        final StringBuilder sb = new StringBuilder();
        String s = "";
        for (final Object o : ol) {
            sb.append(s).append(String.valueOf(o));
            s = sep;
        }
        return sb.toString();
    }

    /**
     * @param sep
     * @param sl
     * @return
     */
    public static String join(final String sep, final String... sl) {
        return join(sep, (Object[]) sl);
    }

    public static int size(Collection<?> c) {
        return (c == null) ? 0 : c.size();
    }
}

Related

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