This post will discuss how to remove empty strings from a List of strings in Java.

1. Using List.removeAll() method

The removeAll() method is commonly used to remove all the elements from the list that are contained in the specified collection. For example, the following code removes all strings that are null or empty from a list of strings:

Download  Run Code

Output:

[A, B, C, D]

2. Using List.removeIf() method

Java 8 introduced several enhancements to the Collection interface, like the removeIf() method, which removes all items from the list satisfying the given predicate.

Download  Run Code

Output:

[A, B, C, D]

 
The above solution makes two calls to the removeIf() method for removing nulls and empty values. You can use Apache Commons Lang StringUtils.isEmpty() method instead, which checks a string is an empty string or null.

Download Code

Output:

[A, B, C, D]

 
This can be answered trivially using lambda expressions without any additional libraries.

Download  Run Code

Output:

[A, B, C, D]

3. Using Stream.filter() method

Here’s a version using Java 8 Streams that filters a collection by applying specified Predicate to each element. If the predicate returns false, it removes the element. Here’s a working example:

Download  Run Code

Output:

[A, B, C, D]

4. Using Iterator

Another solution is to iterate over elements of the list and remove if the current element if it is null and equal to an empty string. You should use the iterator’s own remove() method, to avoid ConcurrentModificationException. See this post for more details on this behavior.

Download  Run Code

Output:

[A, B, C, D]

That’s all about removing empty strings from a List of strings in Java.