Java examples for java.util:Collection Element
Find a value of the given type in the given Collection.
import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; public class Main{ public static void main(String[] argv){ Collection collection = java.util.Arrays.asList("asdf","book2s.com"); Class type = String.class; System.out.println(findValueOfType(collection,type)); }//from w w w . jav a2 s . com /** * Find a value of the given type in the given Collection. * @param collection the Collection to search * @param type the type to look for * @return a value of the given type found, or <code>null</code> if none * @throws IllegalArgumentException if more than one value of the given type found */ public static Object findValueOfType(Collection collection, Class type) throws IllegalArgumentException { if (isEmpty(collection)) { return null; } Class typeToUse = (type != null ? type : Object.class); Object value = null; for (Iterator it = collection.iterator(); it.hasNext();) { Object obj = it.next(); if (typeToUse.isInstance(obj)) { if (value != null) { throw new IllegalArgumentException( "More than one value of type [" + typeToUse.getName() + "] found"); } value = obj; } } return value; } /** * Find a value of one of the given types in the given Collection: * searching the Collection for a value of the first type, then * searching for a value of the second type, etc. * @param collection the collection to search * @param types the types to look for, in prioritized order * @return a of one of the given types found, or <code>null</code> if none * @throws IllegalArgumentException if more than one value of the given type found */ public static Object findValueOfType(Collection collection, Class[] types) throws IllegalArgumentException { if (isEmpty(collection) || ObjectUtils.isEmpty(types)) { return null; } for (int i = 0; i < types.length; i++) { Object value = findValueOfType(collection, types[i]); if (value != null) { return value; } } return null; } /** * Return <code>true</code> if the supplied Collection is <code>null</code> * or empty. Otherwise, return <code>false</code>. * @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</code> if the supplied Map is <code>null</code> * or empty. Otherwise, return <code>false</code>. * @param map the Map to check * @return whether the given Map is empty */ public static boolean isEmpty(Map map) { return (map == null || map.isEmpty()); } }