How to remove all null elements from a ArrayList or String Array?

Juan de Dios picture Juan de Dios · Jan 27, 2011 · Viewed 193.4k times · Source

I try with a loop like that

// ArrayList tourists

for (Tourist t : tourists) {
    if (t != null) {     
        t.setId(idForm); 
    }   
}

But it isn't nice. Can anyone suggest me a better solution?


Some useful benchmarks to make better decision:

While loop, For loop and Iterator Performance Test

Answer

Lithium picture Lithium · Jan 27, 2011

Try:

tourists.removeAll(Collections.singleton(null));

Read the Java API. The code will throw java.lang.UnsupportedOperationException for immutable lists (such as created with Arrays.asList); see this answer for more details.