Check ArrayList for instance of object

public static <T> T getFirstElementOfTypeIn( List<?> list, Class<T> clazz )
{
  for ( Object o : list )
  {
    if ( clazz.isAssignableFrom( o.getClass() ) )
    {
      return clazz.cast( o );
    }
  }
  return null;
}

If you're using Java 8 you can do:

public <T> Optional<T> getInstanceOf(Class<T> clazz, Collection<?> collection) {
    return (Optional<T>) collection.stream()
            .filter(e -> clazz.isInstance(e.getClass()))
            .findFirst();
}

Check the documentation of Optional if you never used it before. Actually this is better practice than returning null.


public static <T> T find(Collection<?> arrayList, Class<T> clazz)
{
    for(Object o : arrayList)
    {
        if (o != null && o.getClass() == clazz)
        {
            return clazz.cast(o);
        }
    }

    return null;    
}

and call

String match = find(myArrayList, String.class);