Filtrado de elementos de una Lista

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?

preguntado el 02 de mayo de 12 a las 19:05

3 Respuestas

best way is to use iterator.remove()

contestado el 02 de mayo de 12 a las 19:05

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.

contestado el 02 de mayo de 12 a las 19:05

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.colecciones.Predicado)

contestado el 02 de mayo de 12 a las 19:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.