我定义了自己的谓词:
public interface StringPredicate extends Predicate<String> {
它有效,但如果我写:
myPred.and( strEl -> strEl != null);
结果是 Predicate<String>
不是StringPredicate
。我如何定义组合操作?
最佳答案
您可以在 StringPredicate
接口(interface)中定义自己的 and
方法:
public interface StringPredicate extends Predicate<String> {
default StringPredicate and(StringPredicate other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
}
现在,以下内容将起作用:
StringPredicate myPred = s -> s.length() > 0;
StringPredicate combined = myPred.and(strEl -> strEl.length () < 5);
关于java - 如何定义自定义组合谓词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62152001/