Ravi
Ravi

Reputation: 301

Predicate chaining question

Below is the object structure -

Requirement : Return a list of B which have atleast one of the elements of C's Predicate P return true .

My current solution has a for loop. I was wondering if this can be done without using a for loop.

Upvotes: 1

Views: 1157

Answers (2)

alpian
alpian

Reputation: 4748

Why does it matter where the Predicate is defined? Do you mean that it's define on C?

// You already have Predicate<C> defined somewhere
Predicate<C> csPredicate = new Predicate<C>() {
    public boolean apply(C c) {
        return someComputationOn(c);
    }
};

Iterables.filter(A.getIterableOfB(), 
    Predicates.compose(
        csPredicate, 
        new Function<B, C>() {
            @Override
            public C apply(B b) {
                return b.getC();
            }
}));

My answer is very similar to sMoZely (+1) except i'm using Iterables.filter() and composing the Predicates instead of using Collections2 but the idea is the same. I may also be missing something in the question...

Upvotes: 4

sMoZely
sMoZely

Reputation: 379

If I understand this correctly ... can't you just create a Predicate for B that calls the Predicate for C?

i.e. in B ...

new Predicate<B>() {
  @Override
  public boolean apply(B record) {
    return new PredicateOverC().apply(record.getC())
  }
}

And then in A you can just use Collections2.filter over the collection of B and this new predicate?

Upvotes: 1

Related Questions