Below is the object structure -
- class
A
has a collection of classB
- class
B
has one to one mapping with classC
- I开发者_运维问答 have a predicate
P
defined inC
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?
精彩评论