Android Collection Element Get findCommonElementType(Collection collection)

Here you can find the source of findCommonElementType(Collection collection)

Description

Find the common element type of the given Collection, if any.

Parameter

Parameter Description
collection the Collection to check

Return

the common element type, or null if no clear common type has been found (or the collection was empty)

Declaration

public static Class<?> findCommonElementType(Collection collection) 

Method Source Code

//package com.java2s;

import java.util.Collection;

import java.util.Map;

public class Main {
    /**/*from   w w  w . j  av a  2s .co m*/
     * Find the common element type of the given Collection, if any.
     * @param collection the Collection to check
     * @return the common element type, or {@code null} if no clear
     * common type has been found (or the collection was empty)
     */
    public static Class<?> findCommonElementType(Collection collection) {
        if (isEmpty(collection)) {
            return null;
        }
        Class<?> candidate = null;
        for (Object val : collection) {
            if (val != null) {
                if (candidate == null) {
                    candidate = val.getClass();
                } else if (candidate != val.getClass()) {
                    return null;
                }
            }
        }
        return candidate;
    }

    /**
     * Return {@code true} if the supplied Collection is {@code null}
     * or empty. Otherwise, return {@code false}.
     * @param collection the Collection to check
     * @return whether the given Collection is empty
     */
    public static boolean isEmpty(Collection collection) {
        return (collection == null || collection.isEmpty());
    }

    /**
     * Return {@code true} if the supplied Map is {@code null}
     * or empty. Otherwise, return {@code false}.
     * @param map the Map to check
     * @return whether the given Map is empty
     */
    public static boolean isEmpty(Map map) {
        return (map == null || map.isEmpty());
    }
}

Related

  1. getFirst(Collection collection)
  2. getLastIndex(final Collection collection)