开发者

Predicate chaining question

Below is the object structure -

  • class A has a collection of class B
  • class B has one to one mapping with class C
  • I开发者_运维问答 have a predicate P defined in C

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.


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...


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜