Web / Apache Commons Collections Interview questions
Why do we use predicate chaining with allPredicate and anyPredicate?
Predicate chaining lets you compose several independent validation rules into a single reusable Predicate object, instead of hard-coding a chain of if/else checks wherever the filtering logic is needed.
Predicate<String> nonEmpty = s -> s != null && !s.isEmpty(); Predicate<String> isShort = s -> s.length() <= 10; Predicate<String> validName = PredicateUtils.allPredicate(nonEmpty, isShort); Predicate<String> flaggable = PredicateUtils.anyPredicate(nonEmpty.negate(), s -> s.startsWith("!")); Collection<String> valid = CollectionUtils.select(names, validName);
allPredicate() gives AND semantics - every sub-predicate must pass - which is useful for compound validation rules like "not blank AND under a length limit." anyPredicate() gives OR semantics - at least one sub-predicate passing is enough - useful for "matches any of several exception cases."
Because the composed Predicate is just another Predicate object, it can be passed straight into CollectionUtils.filter()/select(), reused across multiple call-sites, and further nested inside other allPredicate()/anyPredicate() calls, keeping validation logic centralized and testable in one place instead of duplicated inline.
More Related questions...