Explain Codes LogoExplain Codes Logo

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

java
collections
best-practices
performance
Anton ShumikhinbyAnton Shumikhin·Sep 11, 2024
TLDR

Quick way to get rid of null elements from an ArrayList:

list.removeIf(Objects::isNull); //Like using a bug spray for nulls!

To filter out the nulls in a String[] array:

array = Arrays.stream(array).filter(Objects::nonNull).toArray(String[]::new); //Nulls, fly away!

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:

Iterable<String> filtered = Iterables.filter(list, Predicates.notNull()); //nulls checked at the gate! List<String> result = ImmutableList.copyOf(filtered);

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:

ArrayList<String> tempList = new ArrayList<>(); for (String element : array) { if (element != null) tempList.add(element); //If not null, welcome aboard! } array = tempList.toArray(new String[0]);

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.