Java Collection to String collectionToString(Collection elements)

Here you can find the source of collectionToString(Collection elements)

Description

Converts the specified Collection to a string.

License

Apache License

Parameter

Parameter Description
elements the collection to be converted to a string. This argument can be null , in which case the string "null" is returned.

Return

the string representation of the passed collection. This method never returns null .

Declaration

public static String collectionToString(Collection<?> elements) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.Collection;

public class Main {
    private static final int EXPECTED_ELEMENT_STRING_LENGTH = 32;
    private static final String NULL_STR = "null";

    /**//from  w  w  w.  j  av  a 2 s.  co m
     * Converts the specified {@code Collection} to a string. This method works
     * exactly the same as the {@link #arrayToString(Object[])} method but
     * for collections rather than array. The order of the elements depends
     * on the order the iterator of the collection returns them.
     *
     * @param elements the collection to be converted to a string. This argument
     *   can be {@code null}, in which case the string "null" is returned.
     * @return the string representation of the passed collection. This method
     *   never returns {@code null}.
     *
     * @see #arrayToString(Object[])
     */
    public static String collectionToString(Collection<?> elements) {
        if (elements == null) {
            return NULL_STR;
        }

        int size = elements.size();
        if (size == 0) {
            return "[]";
        } else if (size == 1) {
            return "[" + elements.toArray()[0] + "]";
        } else {
            StringBuilder result = new StringBuilder(EXPECTED_ELEMENT_STRING_LENGTH * elements.size());

            result.append('[');
            for (Object element : elements) {
                result.append('\n');
                result.append(element);
            }
            result.append(']');

            return result.toString();
        }
    }
}

Related

  1. collectionToString(Collection c)
  2. collectionToString(Collection c, String separator)
  3. collectionToString(Collection coll, String connectSymbol)
  4. collectionToString(Collection collection, String separator)
  5. collectionToString(Collection collection, String separator)
  6. collectionToString(Collection list)
  7. collectionToString(Collection list)
  8. collectionToString(Collection collection, String prefix)
  9. collectionToString(Collection collection)

    HOME | Copyright © www.java2s.com 2016