Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find matching predicate and using iterable.tryFind return the element from the list in java

Tags:

java

guava

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 ?

like image 718
LifeStartsAtHelloWorld Avatar asked May 21 '14 01:05

LifeStartsAtHelloWorld


1 Answers

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();
like image 200
phlogratos Avatar answered Oct 25 '22 15:10

phlogratos