java - 在 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>)
,但这会引发运行时错误,表明无法强制转换。我该如何克服呢?
解决方案
isNotPartitionFile
应定义为:
Predicate<Path> isNotPartitionFile = path -> !path.toString().contains("partition");
因为filter
消耗了一个Predicate<T>
not Function<T, R>
。
推荐阅读
- ruby-on-rails - Rails API ActiveStorage DirectUpload 产生 422 错误 InvalidAuthenticityToken
- sorting - Google 表格上的简单排序脚本不起作用
- html - 如何设置具有不同引导响应尺寸的图像的最大宽度?
- javascript - How to trigger Jquery slide effect only when a specific option is selected and button is clicked?
- python - 如果我的登录路径从 Flask 中的表单中读取信息,如何让假测试用户登录 pytest
- elasticsearch - 在弹性搜索嵌套对象中应用多个过滤器
- php - 获取 PHP 类之外的常量列表
- google-cloud-sql - 如何在 Event OnBeforeCreate 上使用数据库数据
- swift - 如果没有在 Swift 中加载奖励广告,如何隐藏 UIButton?
- amazon-web-services - 服务器上保存凭据和apikey的最佳位置是什么?