Java filter list to generic type T

What should I do (without compiling):

<T> List<T> getElementsOf() {
    return list.stream()
            .filter(x -> x instanceof T)
            .map(x -> (T) x)
            .collect(toList());
}

What are examples of usage? Ideally, it should look like obj< Derived> getElementsOf().

Solution

Although another answer almost completes the work, here is a better answer:

<T> List<T> getElementsOf(Class<T> clazz) {
    return list.stream()
            .filter(clazz::isinstance)
            .map(clazz::cast)
            .collect(toList());
}

Notice clazz:: isinstance thingy Instead of comparing two classes, it uses the isinstance method According to the documentation, this is equivalent to instanceof, which is the first one you want

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>