Converts collection to array of strings - Java Collection Framework

Java examples for Collection Framework:Array Convert

Description

Converts collection to array of strings

Demo Code


//package com.java2s;
import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        System.out.println(java.util.Arrays
                .toString(toStringArray(collection)));
    }/*  www. j a  v  a 2s  . co  m*/

    /**
     * Converts collection to array of strings
     * @param collection source collection
     */
    public static String[] toStringArray(Collection collection) {
        if (collection == null) {
            return null;
        }
        if (collection.isEmpty()) {
            return new String[] {};
        }
        int index = 0;
        String[] result = new String[collection.size()];
        for (Object item : collection) {
            if (item == null) {
                result[index++] = null;
            }
            result[index++] = String.valueOf(item);
        }
        return result;
    }
}

Related Tutorials