Question

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.

Was it helpful?

Solution 2

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]

OTHER TIPS

Can't you just swallow the exception?

try
{
    predicatedList.add(null);
}
catch(IllegalArgumentException e)
{ 
    //ignore the exception
}

You'd probablly need to write a wrapper to do this for you...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top