Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all elements of a list by instance?

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?

like image 354
membersound Avatar asked Mar 30 '15 08:03

membersound


1 Answers

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());
}
like image 144
Konstantin Yovkov Avatar answered Nov 14 '22 23:11

Konstantin Yovkov