Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need Predicate functional interface in Java?

Why we need Predicate interface? I didn't understand below code. How can I find result of primaryPaxOutput alternatively?

    Predicate<TravellerType> predicate1 = new Predicate<TravellerType>() {
        @Override
        public boolean apply(TravellerType input) {
            return PassengerCodeUtil.paxCodesEqual(input.getTravellerType().getCode(), "CHD");
        }
    };

    primaryPaxOutput = Iterables.tryFind(result.getTravellerTypes(), predicate1).orNull();
like image 783
Arif Acar Avatar asked Feb 26 '26 01:02

Arif Acar


1 Answers

Predicates are great for abstracting out entire functions into whatever type of result they produce, which increases readability and reusability. This is true for both Guava and Java versions of the interface. Predicates should be well-named, so in this example it's a bit hard to understand what's going on.

I have no idea what a TravellerType or PassengerCode is, but for the sake of argument let's rename the Predicate to whatever it does.

We can then code our iterables statement to be:

primaryPaxOutput = Iterables.tryFind(result.getTravellerTypes(), paxCodeIsCHD).orNull();

We then interpret this statement as:

Iterables.tryFind(            //Find the first instance
result.getTravellerTypes(),   //among this Iterable
paxCodeIsCHD                  //where this predicate is true
).orNull();                   //or else set to null.

If you know what tryFind does, then this code becomes much more readable than injecting an anonymous class or even a lambda as a parameter.

like image 121
Zircon Avatar answered Feb 28 '26 13:02

Zircon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!