我需要使用基于 boolean 函数的谓词组合流操作。通过将方法的参数作为谓词重新抛出来找到解决方法,如下所示:
public <T> Predicate<T> pred(final Predicate<T> aLambda) {
return aLambda;
}
public List<String> foo() {
return new ArrayList<String>().stream() //of course, this does nothing, simplified
.filter(pred(String::isEmpty).negate())
.collect(Collectors.toList());
}
'pred' 方法似乎什么都不做,但不是这个:
public List<String> foo() {
return new ArrayList<String>().stream()
.filter((String::isEmpty).negate())
.collect(Collectors.toList());
}
也没有任何内联转换:
public List<String> foo() {
return new ArrayList<String>().stream()
.filter(((Predicate)String::isEmpty).negate())
.collect(Collectors.toList());
}
似乎有效。失败并出现错误
The target type of this expression must be a functional interface
'pred(...)' 方法中发生了什么奇妙的转换?
最佳答案
你可以写一个实用方法:
class PredicateUtils {
public static <T> Predicate<T> not(Predicate<T> predicate) {
return predicate.negate();
}
}
并按如下方式使用它:
.filter(not(String::isEmpty))
我相信它比转换为 Predicate<T>
更具可读性:
.filter(((Predicate<String>)String::isEmpty).negate())
虽然我会选择一个简单的 lambda:
s -> !s.isEmpty()
What the fancy conversion happens in the
pred(...)
method?
您已经指定了一个上下文——要使用的类型。例如,String::isEmpty
可能是 Function<String, Boolean>
, 或 Predicate<String>
,或者我的 @FunctionalInterface
,或其他东西。
您明确表示您期待一个 Predicate<T>
,您将返回 Predicate<T>
的一个实例.编译器现在能够确定您要使用的类型。
关于java - 来自函数引用的谓词( boolean 类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48524357/