Method to convert a Collection to a List collection. - Java java.util

Java examples for java.util:Collection Convert

Description

Method to convert a Collection to a List collection.

Demo Code


import java.lang.reflect.Array;
import java.util.*;

public class Main{
    public static void main(String[] argv){
        Object collection = "book2s.com";
        System.out.println(toList(collection));
    }/* www.  j a  v  a  2  s .c om*/
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory
            .getLogger(CollectionUtilities.class);
    /**
     * Method to convert a Collection to a List collection.
     * @param <T> generic type.
     * @param collection the Collection object.
     * @return the List object.
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> toList(Object collection) {
        if (isCollection(collection)) {
            if (collection instanceof Enumeration)
                return Collections.list((Enumeration<T>) collection);
            if (collection instanceof TreeSet)
                return new ArrayList<>((TreeSet<T>) collection);
            //if(collection instanceof Set) return SetUtilities.toList((Set<T>) collection);
            if (collection instanceof Iterable) {
                if (collection instanceof List)
                    return (List<T>) collection;
                else {
                    List<T> list = new ArrayList<>();
                    for (T e : (Iterable<T>) collection) {
                        list.add(e);
                    }
                    return list;
                }
            }
            if (collection instanceof Object[])
                return ArrayUtilities.toList((T[]) collection);
            if (collection instanceof Iterator) {
                List<T> list = new ArrayList<>();
                Iterator<T> iterator = (Iterator<T>) collection;
                while (iterator.hasNext()) {
                    list.add(iterator.next());
                }
                return list;
            } else
                return new ArrayList<>();
        } else {
            logger.error("The object:" + collection
                    + " is not a Collection");
            return new ArrayList<>();
        }
    }
    /**
     * Method to check if a Object is a Collection or not.
     * @param ob the Object to inspect.
     * @return if true the class extend or implememnt Collection.
     */
    public static boolean isCollection(Object ob) {
        return ob instanceof Collection || ob instanceof Map;
        //return ob != null && isClassCollection(ob.getClass());
    }
}

Related Tutorials