Java Collection Join joinAsString(Collection collection, String separator)

Here you can find the source of joinAsString(Collection collection, String separator)

Description

Join each element in a collection using a string separator

License

Open Source License

Parameter

Parameter Description
collection The collection to join
separator The separator to use

Return

A string where the toString method on each object in the collection has been called and each element is separated with the separator string.

Declaration

public static String joinAsString(Collection<? extends Object> collection, String separator) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 ?ystein Idema Torget and others
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from w w  w  .ja v  a  2 s . c om
 *     ?ystein Idema Torget and others
 *******************************************************************************/

import java.util.Collection;

public class Main {
    /**
     * Join each element in a collection using a string separator
     * @param collection The collection to join
     * @param separator The separator to use
     * @return A string where the toString method on each object in the collection has been called and each element is
     * separated with the separator string.
     */
    public static String joinAsString(Collection<? extends Object> collection, String separator) {

        if (collection.isEmpty()) {
            return "";
        }

        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Object o : collection) {

            if (first) {
                first = false;
            } else {
                result.append(separator);
            }
            result.append(o.toString());

        }
        return result.toString();
    }
}

Related

  1. join(String[] collection, String delimiter)
  2. join(String[] collection, String separator)
  3. join(StringBuilder builder, Collection strs)
  4. join2(Collection list, String delimiter)
  5. joinAndDelimit(final Collection strings, final String sep, final String delim)
  6. joinAsStrings(Collection values, String separator)
  7. joinCol(Collection lst, String delim)
  8. joinCollection(Collection collection, char delimiter)
  9. joinCollection(Collection a)