Java Collection to String toStrings(final Collection stringCollection)

Here you can find the source of toStrings(final Collection stringCollection)

Description

to Strings

License

Creative Commons License

Declaration

static public String[] toStrings(final Collection<String> stringCollection) 

Method Source Code

//package com.java2s;
/**/*from ww  w .  j a v  a  2 s.  c om*/
 * Utilities for Strings.
 * <H3><I><FONT color="#770000">Subset of original source.</FONT></I></H3>
 *
 * @author <SMALL>Copyright 2012 by Stephen Baber
 * &nbsp; <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/deed.en_US">
 * <img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-sa/3.0/80x15.png" /></a><br />
 * This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/deed.en_US">
 * Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.</SMALL>
 */

import java.util.Collection;

public class Main {
    static final public String[] NO_STRINGS = new String[0];

    static public String[] toStrings(final Collection<String> stringCollection) {
        switch (stringCollection.size()) {
        case 0:
            return NO_STRINGS;
        case 1:
            return new String[] { stringCollection.iterator().next() };
        default:
            return stringCollection.toArray(new String[stringCollection.size()]);
        }
    }

    /**
     * Non-deep scan, just flat transform to new String[].
     *
     * @param objs can contain 'null' elements
     * @return 'null' elements are assigned ""
     */
    static public String[] toStrings(final Object[] objs) {
        switch (objs.length) {
        case 0:
            return NO_STRINGS;
        case 1:
            return new String[] { objs[0].toString() };
        default: {
            final String[] strings = new String[objs.length];
            int i = 0;
            for (final Object obj : objs) {
                strings[i] = (obj != null) ? obj.toString() : "";
                i++;
            }
            return strings;
        }
        }
    }
}

Related

  1. toString(final Collection c)
  2. toString(String[] collection, char separator)
  3. toStrings(Collection vals)
  4. toStrings(Collection c)
  5. toStrings(Collection objects)
  6. toStringWithDelimiters(Collection objects, String delim)
  7. toStringWithSeparator(Collection collection, String separator)