Method to convert a Collection to Iterator object. - Java java.util

Java examples for java.util:Collection Convert

Description

Method to convert a Collection to Iterator object.

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(toIterator(collection));
    }//from www  .ja v  a  2  s . com
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory
            .getLogger(CollectionUtilities.class);
    /**
     * Method to convert a Collection to Iterator object.
     * @param <T> generic type.
     * @param collection the Collection.
     * @return the Iterator object.
     */
    @SuppressWarnings("unchecked")
    public static <T> Iterator<T> toIterator(Object collection) {
        if (isCollection(collection)) {
            if (collection instanceof List)
                return ((List<T>) collection).iterator();
            if (collection instanceof Set)
                return ((Set<T>) collection).iterator();
            else {
                return new Iterator<T>() {
                    @Override
                    public boolean hasNext() {
                        return false;
                    }

                    @Override
                    public T next() {
                        return null;
                    }

                    @Override
                    public void remove() {
                    }
                };
            }
        } else {
            logger.error("The object:" + collection
                    + " is not a Collection");
            return new Iterator<T>() {
                @Override
                public boolean hasNext() {
                    return false;
                }

                @Override
                public T next() {
                    return null;
                }

                @Override
                public void remove() {
                }
            };
        }
    }
    /**
     * 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