java - 用 Streams 替换 guava Fluent Iterables

标签 java generics java-8 java-stream guava

我有一个按类型过滤的方法,它作为输入 Collection<?> collectionClass<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/

相关文章:

java - 用连续范围的短裤填充列表

java - 为什么 lambda 表达式不写 `.class` 而内部类写

<JDK8 兼容性中的 Java 三元运算符与 if/else

java - 通过Java启动appium服务器

java - 使用通用接口(interface)时不调用 EJB 拦截器

java - 如何使用 mvc 在数据库中存储图像或任何类型的文档

c# - 泛型与接口(interface)的实际优势

C# Func<> 和泛型

java - 尝试将对象传递给常规模板Play Framework 1.2时出现内存不足异常

java - Kafka java消费者SSL握手错误: java. security.cert.CertificateException:不存在主题替代名称