Java Collection to String collectionToString(Collection collection, String delimiter)

Here you can find the source of collectionToString(Collection collection, String delimiter)

Description

Converts all the objects from the collections to a string and separates them using a delimiter.

License

Open Source License

Parameter

Parameter Description
collection a parameter
delimiter a literal or a character to be used to separate the string.

Declaration

public static String collectionToString(Collection<? extends Object> collection, String delimiter) 

Method Source Code


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

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Main {
    /**//from   w  w w. java 2s  .com
     * Converts all the objects from the collections to a string and separates
     * them using a delimiter. toString() of the object that is contained in the
     * collection must be override to get better user if the class is other then
     * String and Wrapper types.
     *
     * @param collection
     * @param delimiter a literal or a character to be used to separate the
     * string.
     * @return
     */
    public static String collectionToString(Collection<? extends Object> collection, String delimiter) {
        StringBuilder result = new StringBuilder();
        List<Object> list = new ArrayList<>();
        list.addAll(collection);
        if (delimiter == null) {
            delimiter = ",";
        }
        for (Object obj : list) {
            result.append(obj.toString());
            if (list.indexOf(obj) + 1 < list.size()) {
                result.append(delimiter);
            }
        }
        return result.toString();
    }
}

Related

  1. collectionToString(Collection coll)
  2. collectionToString(Collection collection, String delim)
  3. collectionToString(Collection list, String split)
  4. collectionToString(Collection set)
  5. collectionToString(Collection c)
  6. collectionToString(Collection collection, String seperator)
  7. collectionToString(Collection list, String delimiter)
  8. collectionToString(Collection c)
  9. collectionToString(Collection c)