convert Collection<String> to String[] array - Java Collection Framework

Java examples for Collection Framework:Array Convert

Description

convert Collection<String> to String[] array

Demo Code


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

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        Collection c = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(java.util.Arrays.toString(convert(c)));
    }/*  w w  w  .  j  av a2s.c  om*/

    public static String[] convert(Collection<String> c) {
        if (c == null)
            return null;

        String[] r = new String[c.size()];
        int i = 0;
        for (String s : c) {
            r[i] = s;
            i++;
        }
        return r;
    }

    public static List<String> convert(String[] c) {
        List<String> l = new ArrayList<String>();
        if (c != null) {
            for (String s : c) {
                if (s != null) {
                    l.add(s);
                }
            }
        }
        return l;
    }
}

Related Tutorials