Check ArrayList for example object

I have a java method which should check through ArrayList and check if it contains an instance of this class. I need to pass the type of the class to the method to check as a parameter, and if List contains an object of this type, return it.

Is this achievable?

+6
source share
4 answers
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); 
+17
source
 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; } 
+4
source

If you are using Java 8, you can:

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

Check the Optional documentation if you have not used it before. This is actually better than returning null .

+1
source

You can iterate over the list and test each item

 Class<?> zz = String.class; for (Object obj : list) { if (zz.isInstance(obj)) { System.out.println("Yes it is a string"); } } 

Note that isInstance also captures subclasses. Otherwise, see Bel's answer.

0
source

Source: https://habr.com/ru/post/890547/


All Articles