How to efficiently remove all null elements from a ArrayList or String Array?
Quick way to get rid of null elements from an ArrayList:
To filter out the nulls in a String[] array:
Use removeIf to clean up ArrayList in situ, or Streams to create a compact array.
Immutable lists and UnsupportedOperationException
When working with immutable lists such as those returned by Collections.unmodifiableList or Arrays.asList(), trying to modify the list with removeIf would cause a java.lang.UnsupportedOperationException. Always study the nature of the list implementation before you proceed.
Checking performance with benchmarks
Performance is a key aspect, especially when your list has a big size. Run benchmarks before deciding on a method - removeIf is quick, but sometimes you might need other approaches such as pre-sorted lists or even third-party libraries for handling complex criteria.
Null-checking with Guava
Guava offers you additional options. To remove null elements, use Iterables.filter together with Predicates.notNull() like this:
Guava can provide both readability and efficiency, often performing better than traditional loops.
Additional tips for handling null in collections
Going direct for arrays
If you're dealing directly with arrays, there is no need to convert them into lists. Use a while loop or for-each loop to kick nulls out:
Mutability of collections
Do your homework before manipulating the collections. Arrays.asList() creates lists which are bound by the original array size and can't be structurally modified.
Working with immutable collections
Working with immutable collections can safeguard your data integrity by blocking unintentional changes. However, this benefits come with the caveat of needing to create new collections after filtering.
Was this article helpful?