I have a list and I want an element from the list which matches a predicate. I am finding an element from the list which matches the first predicate, if the first predicate does not return true, it matches with the second predicate.
Here is an example:
Case1:
result = iterable.tryFind(List, Predicates.or(predicate1, predicate2)).orNull();
The issue with this piece of code is it finds the first element which matches any of those predicates. Even if the second element in the list is matching the first predicate, which in my case should be given higher priority.In this case, I am expecting the result here as a second element, but getting first element (as it is the first element which is matching one of those predicates).
Case2:
result = iterable.tryFind(List, Predicates.and(predicate1, predicate2)).orNull();
This will obviously not work, if the first predicate returns false.
Case 3:
result = iterable.tryFind(List, predicate1).orNull();
if(result == null)
result = iterable.tryFind(List, predicate2).orNull();
This will work for me, but it looks messy and defeats the purpose of functional programming.
Is there any other way to fetch an element from a list that will work for my scenario ?
You can use Optional.or
instead of Predicate.or
to get what you want:
result = Iterables.tryFind(list, predicate1)
.or(Iterables.tryFind(list, predicate2))
.orNull();
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