How to get all 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 for extracting 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());
}
using:
List<Foo> list;
List<Bar> bars = Util.getFromList(list, Bar.class);
Result: It works, but I have to add @SuppressWarnings
due to the unchecked cast
of (List<T>)
. How can I avoid this?
Introducing another type parameter that extends S
is correct, however, in order to have the result as List<S>
, but not as List<T>
, you have to .map()
the entries that pass 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 suggested by @Eran, this can be even simplified to work with just 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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With