Search code examples
javaapicollectionsapache-commons

Apache commons PredicatedList with no IllegalArgumentException


Is there a way in Apache Commons Collections to have a PredicatedList (or similar) which does not throw an IllegalArgumentException if the thing you are trying to add doesn't match the predicate? If it does not match, it would just ignore the request to add the item to the list.

So for example, if I do this:

List predicatedList = ListUtils.predicatedList(new ArrayList(), PredicateUtils.notNullPredicate());
...
predicatedList.add(null); // throws an IllegalArgumentException 

I'd like to be able to do the above, but with the adding of null being ignored with no exception thrown.

I can't figure out from the JavaDocs if Commons Collections supports this. I'd like to do this if possible without rolling my own code.


Solution

  • Just found CollectionUtils.filter. I can probably rework my code to use this, although it would still have been nice to quietly prevent the additions to the list in the first place.

        List l = new ArrayList();
        l.add("A");
        l.add(null);
        l.add("B");
        l.add(null);
        l.add("C");
    
        System.out.println(l); // Outputs [A, null, B, null, C]
    
        CollectionUtils.filter(l, PredicateUtils.notNullPredicate());
    
        System.out.println(l); // Outputs [A, B, C]