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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With