get Type Of First Element from Collection - Java java.util

Java examples for java.util:Collection First Element

Description

get Type Of First Element from Collection

Demo Code


//package com.book2s;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "book2s.com");
        System.out.println(getTypeOfFirstElement(collection));
    }//from  w  w w  . j  a  v a  2s  . c  om

    public static Class<?> getTypeOfFirstElement(Collection<?> collection) {
        if (collection.isEmpty()) {
            return null;
        } else {
            return getFirstObject(collection).getClass();
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List asList(Iterable iterable) {
        List result = new ArrayList();

        for (Object item : iterable) {
            result.add(item);
        }

        return result;
    }

    public static Object getFirstObject(Collection<?> collection) {
        Iterator<?> iterator = collection.iterator();

        if (iterator.hasNext()) {
            return iterator.next();
        } else {
            return null;
        }
    }
}

Related Tutorials