Web / Apache Commons Collections Interview questions
What is a PredicatedCollection in Apache Commons Collections?
A PredicatedCollection is a decorator that wraps an existing Collection and validates every element against a supplied Predicate before allowing it to be added.
Predicate<String> nonEmpty = s -> s != null && !s.isEmpty(); Collection<String> validated = PredicatedCollection.predicatedCollection(new ArrayList<>(), nonEmpty); validated.add("ok"); // succeeds validated.add(""); // throws IllegalArgumentException immediately
Because the check runs at add-time rather than being scattered across every call-site that inserts data, the collection's contents are guaranteed valid the instant they enter it, with a clear, fail-fast error if something doesn't qualify.
Related decorators - PredicatedList, PredicatedSet, PredicatedMap, and PredicatedBag - apply the exact same idea to their respective collection types.
More Related questions...