Phate
Phate

Reputation: 6612

How to define custom combine predicate?

I defined my own predicate:

public interface StringPredicate extends Predicate<String> {

It works, but if I write:

myPred.and( strEl -> strEl != null);

the result is a Predicate<String> not a StringPredicate. How can I define a combine operation as well?

Upvotes: 2

Views: 429

Answers (1)

Eran
Eran

Reputation: 393831

You can define your own and method in your StringPredicate interface:

public interface StringPredicate extends Predicate<String> {
    default StringPredicate and(StringPredicate other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
}

Now, the following will work:

StringPredicate myPred = s -> s.length() > 0;
StringPredicate combined = myPred.and(strEl -> strEl.length () < 5);

Upvotes: 3

Related Questions