繁体   English   中英

在 Java 8 中使用函数式接口作为 filter() 函数的参数

[英]Using functional interface as parameters to filter() function in Java 8

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

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>而不是Function<T, R>

这应该工作,

Predicate<Path> isNotPartitionFile = path -> {
    if (!path.toString().contains("partition")) {
        return true;
    }
    return false;
};

Predicate接口包含方法test(),该方法带有一个参数并返回一个Boolean值。 您只需传递一个Path ,它就会返回一个Boolean值。

Predicate是一个函数,它接受一个值并始终返回boolean .filter期待Predicate<T>而不是Function<T, Boolean> Predicate<T>不扩展Function<T, Boolean>的原因是Predicate<T>返回永远不能为空的boolean值。 要解决您的问题,您可以将isNotPartitionFile更改为

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

我自己想出了解决方案。

filter函数需要一个函数作为参数,但传递了一个函数接口。 所以需要换成Function接口的apply函数。

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

Stream<T> filter(Predicate<? super T> predicate)应用 Predicate 作为参数。

Predicate是一个布尔值函数。

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM