Creates an array of the specified class and populate it with items of the specified Iterable . - Java Collection Framework

Java examples for Collection Framework:Iterable

Description

Creates an array of the specified class and populate it with items of the specified Iterable .

Demo Code


//package com.java2s;
import java.lang.reflect.Array;
import java.util.Arrays;

import java.util.LinkedList;
import java.util.List;

public class Main {
    /**//from  w w  w  .ja v a  2  s .c  om
     * Creates an array of the specified class and populate it with items of the specified {@link Iterable}.
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] arrayOf(Iterable<T> it, Class<T> clazz) {
        final List<T> list = listOf(it);
        final T[] result = (T[]) Array.newInstance(clazz, list.size());
        int i = 0;
        for (final T t : it) {
            result[i] = t;
            i++;
        }
        return result;
    }

    /**
     * Returns a list form the the specified {@link Iterable}.
     * If the specified {@link Iterable} is yet a {@link List} than it
     * is returned as is, otherwise a brand new {@link List} is created.
     */
    public static <T> List<T> listOf(Iterable<T> it) {
        if (it instanceof List) {
            return (List<T>) it;
        }
        final List<T> result = new LinkedList<T>();
        for (final T t : it) {
            result.add(t);

        }
        return result;
    }

    /**
     * @see #listOf(Iterable)
     */
    public static <T> List<T> listOf(T... items) {
        return Arrays.asList(items);
    }
}

Related Tutorials