James P.
James P.

Reputation: 19607

Filtering elements out of a List

Say you want to filter elements out of a List. Running this code triggers something like a concurrency exception as the list is being modified during the loop:

List<String> aList = new ArrayList<String>();

// Add instances to list here ...

for( String s : aList ){
    if( "apple".equals( s ) ){ // Criteria
        aList.remove(s);
    }
}

What is the conventional way of doing this and what other approaches do you know of?

Upvotes: 1

Views: 540

Answers (3)

Martin Smith
Martin Smith

Reputation: 76

Agree with the above two if you're iterating or have a collection of simple elements. If your condition or objects are more involved, consider Apache Commons CollectionUtils' filter method, which allows you to define a predicate encapsulating your condition and which is then applied to each element of the collection. Given your collection aList and a predicate applePredicate, the method of invocation would then be:

org.apache.commons.collections.CollectionUtils.filter(aList, applePredicate);

http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html#filter(java.util.Collection, org.apache.commons.collections.Predicate)

Upvotes: 1

Mik378
Mik378

Reputation: 22171

For your case, you can simply use a solution without any iteration manually done (removeAll takes care about this):

aList.removeAll("apple");

It removes all "apple" elements from the list.

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

best way is to use iterator.remove()

Upvotes: 3

Related Questions