Java – how do I get all the elements of a list through an instance?

How do I get all the elements of a list by instance?

I have a list that can have any class implementation of an interface foo:

interface Foo;
class Bar implements Foo;

I want to use the java8 stream API to provide a utility method to extract all elements of a specific class type:

public static <T extends Foo> List<T> getFromList(List<Foo> list,Class<T> type) {
    return (List<T>) list.stream().filter(entry -> type.isinstance(entry)).collect(Collectors.toList());
}

use:

List<Foo> list;
List<Bar> bars = Util.getFromList(list,Bar.class);

Result: it works, but due to unchecked cast (list < T >), I have to add @ suppresswarnings How can I avoid this?

Solution

It is correct to introduce another type parameter of extension s, but in order to treat the result as list < s > instead of list < T >, you must Map() passes the type:: isinstance predicate to s

public static <T extends Foo,S extends T> List<S> getFromList(List<T> list,Class<S> type) {
    return list.stream()
               .filter(type::isinstance)
               .map(type::cast)
               .collect(Collectors.toList());
}

As @ ERAN suggests, this can even be simplified to using only one type parameter:

public static <T extends Foo> List<T> getFromList(List<Foo> list,Class<T> type) {
    return list.stream()
               .filter(type::isinstance)
               .map(type::cast)
               .collect(Collectors.toList());
}
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
分享
二维码
< <上一篇
下一篇>>