首页 > 解决方案 > 在 Java 8 中使用函数式接口作为 filter() 函数的参数

问题描述

这是一个尝试在过滤器函数中使用功能接口的代码片段。

Function<Path, Boolean> isNotPartitionFile = (path) -> {
    return !path.toString().contains("partition");
};

List<Path> pathsList =  Files.walk(Paths.get(extractFilesLocation))
                                 .filter(Files::isRegularFile)
                                 .filter(isNotPartitionFile)
                                 .collect(Collectors.toList());

当我尝试将isNotPartitionFile用作函数的参数时filter(),eclipse 会弹出一个错误,显示The method filter(Predicate<? super Path>) in the type Stream<Path> is not applicable for the arguments (Function<Path,Boolean>). 它还建议强制转换为(Predicate<? super Path>),但这会引发运行时错误,表明无法强制转换。我该如何克服呢?

标签: javajava-8java-streamfunctional-interface

解决方案


isNotPartitionFile 应定义为:

Predicate<Path> isNotPartitionFile = path -> !path.toString().contains("partition");

因为filter消耗了一个Predicate<T>not Function<T, R>


推荐阅读