views:

145

answers:

2

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.

+1  A: 

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...

masher
Thanks. I'd like to do it with just library code. But I'm coming to the same conclusion that I'd have to write my own wrapper to swallow the exception.
A_M
A: 

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]
A_M