Getting the collection of the most common type from the GenericType <T> .class filter

I apologize in advance for the terrible title, suggestions for improvement are eagerly accepted.

Let's say I have a method that filters List<T>an arbitrary type based on class, returning a new Listone whose elements are those from the input list that are instances of this class. Here's a simple implementation (yes, you can also do this in a 1-liner with threads):

public static <T> List<T> filterByClass(List<?> list, Class<T> clazz) {
    List<T> filtered = new ArrayList<>();
    for (Object o : list) {
        if (clazz.isInstance(o)) {
            filtered.add(clazz.cast(o));
        }
    }
    return filtered;
}

This works fine if you pass it a list of a non-generic type, such Stringas in (prints foo bar):

List<Object> l = Arrays.<Object>asList(1, "foo ", 2, "bar ");
filterByClass(l, String.class).stream().forEach(System.out::println);

Now I want to pass the filter to a generic class, say Optional<T>:

List<Object> l = Arrays.<Object>asList(1, Optional.of("foo"), 2, Optional.of("bar"));
filterByClass(l, Optional.class).stream().forEach(System.out::println);

This works great and prints:

Optional[foo]
Optional[bar]

, . filterByClass List<Optional>, List<Optional<...>>. raw ..

, , class - Optional<String>.class Optional<Integer>.class - Optional.class.

, - , : : List<Optional<?>>. , Optional Optional<?>, ?

, List<Optional> List<Optional<?>>

List<Optional<?>> r = filterByClass(l, Optional.class);  

, ( , Foo<T> Foo<U> T U).

, , , List, :

List<Optional<?>> r = (List)filterByClass(l, Optional.class);  

, , , Optional<?> class, filterByClass - , , class type .

, filterByClass, - ?

, (.. filterByClass(..., Optional.class) List<Optional<?>>, .

+3
1

filterByClass :

public static <T> List<T> filterByClass(List<?> list, Class<? extends T> clazz) {...}

T :

List<Object> l = Arrays.<Object>asList(1, Optional.of("foo"), 2, Optional.of("bar"));
List<Optional<?>> result = filterByClass(l, Optional.class);

, raw Optional Optional<?> ( ), Class<Optional> Class<? extends Optional<?>>, Optional, cast Optional<?>.

+4

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


All Articles