Java List to Array toArray(Collection list)

Here you can find the source of toArray(Collection list)

Description

Converts a collection ( List , Set ...) of objects to a String array.

License

Open Source License

Parameter

Parameter Description
list Input list

Return

String array (empty array if list = null )

Declaration

public static String[] toArray(Collection list) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 Pablo Pavon-Marino.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * Contributors://from ww w .  jav  a2  s. c o  m
 *     Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1
 *     Pablo Pavon-Marino - from version 0.4.0 onwards
 ******************************************************************************/

import java.util.Collection;
import java.util.Iterator;

public class Main {
    /**
     * Converts a collection ({@code List}, {@code Set}...) of objects to a {@code String} array. If objects are not instances of {@code String}, {@code toString()} will be used.
     *
     * @param list Input list
     * @return {@code String} array (empty array if {@code list} = {@code null})
     * 
     */
    public static String[] toArray(Collection list) {
        if (list == null)
            return new String[0];

        String[] out = new String[list.size()];
        int i = 0;
        Iterator it = list.iterator();
        while (it.hasNext())
            out[i++] = it.next().toString();

        return out;
    }
}

Related

  1. listToArray(List list)
  2. ListToArray(List> values)
  3. listToArray(List list)
  4. listToArray(List stringList)
  5. listToArray(List list)
  6. toArray(Collection list)
  7. toArray(final List list)
  8. toArray(final List list)
  9. toArray(final List list)