如何通过实例获取列表的所有元素?
我有一个列表,可以包含接口(interface)的任何类实现 Foo
:
interface Foo;
class Bar implements Foo;
我想使用java8 stream
api 提供用于提取特定类类型的所有元素的实用方法:
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());
}
使用:
List<Foo> list;
List<Bar> bars = Util.getFromList(list, Bar.class);
结果:有效,但我必须添加 @SuppressWarnings
由于 unchecked cast
的 (List<T>)
.我怎样才能避免这种情况?
最佳答案
引入另一个扩展 S
的类型参数但是,为了得到 List<S>
的结果是正确的, 但不是 List<T>
, 你必须 .map()
通过 type::isInstance
的条目谓词 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());
}
根据 @Eran 的建议,这甚至可以简化为只使用一个类型参数:
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());
}
关于java - 如何通过实例获取列表的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29341521/