我有一个按类型过滤的方法,它作为输入 Collection<?> collection
和Class<T> tClass
。我想更换FluentIterable
通过Stream
.
public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
return FluentIterable.from(filerCollection).filter(classType).toList();
}
我尝试过这个解决方案:
public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
return (List<T>) filter.stream()
.filter(Objects::nonNull)
.map(Object.class::cast)
.collect(Collectors.toList());
}
如何在不强制返回的情况下做到这一点 Stream
?
最佳答案
您忘记检查您的元素是否属于 T
类型。 IE。您必须首先过滤掉这些元素:
return filter.stream()
.filter(classType::isInstance) // only keep elements of type T
.map(classType::cast) // safely cast from Object to T
.collect(Collectors.toList()); // collect into a List<T>
Class#isInstance()
还直接照顾null
值,因此您不必使用 filter(Object::nonNull)
.
关于java - 用 Streams 替换 guava Fluent Iterables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56332373/