Java examples for java.util:Collection Convert
Method to convert a List Collection to Iterable object.
import java.lang.reflect.Array; import java.util.*; public class Main{ public static void main(String[] argv){ Object collection = "book2s.com"; System.out.println(toIterable(collection)); }//w ww .j a va2s . c om private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory .getLogger(CollectionUtilities.class); /** * Method to convert a List Collection to Iterable object. * @param <T> generic type. * @param collection the Collection. * @return the Iterable object. */ @SuppressWarnings("unchecked") public static <T> Iterable<T> toIterable(final Object collection) { if (isCollection(collection)) { //if(collection instanceof List)return toSet((List<T>)collection); if (collection instanceof Set) return toList(((Set<T>) collection)); if (collection instanceof Object[]) return Arrays.asList((T[]) collection); if (collection instanceof Iterator) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return (Iterator<T>) collection; } }; } else { return new Iterable<T>() { @Override public Iterator<T> iterator() { return null; } }; } } else { logger.error("The object:" + collection + " is not a Collection"); return new Iterable<T>() { @Override public Iterator<T> iterator() { return null; } }; } } /** * 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()); } /** * 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<>(); } } }