This post will discuss how to filter null, empty, and blank values from a list in Java.

1. Using Plain Java

In plain Java, you can use Stream API to filter null, empty, and blank values from a list.

The Stream API provides the filter() method to retain elements that match the specified predicate. In order to remove null, empty, and blank values from a list, you can use the inverse predicate Predicate.not() starting Java 11 and lambda expressions before Java 11.

 
The following program demonstrates the working of the filter() method to remove null, empty, and blank values. Note that the solution creates a copy of the original list.

Download  Run Code

2. Using Apache Commons Lang

If your project uses Apache Commons Lang, you can simply use isNotEmpty() or isNotBlank() method from the StringUtils class, which are null-safe. The following program demonstrates the working of these methods. Note that the solution creates a copy of the original list.

Download Code

Output:

[A, B, C, D, E, ]
[A, B, C, D, E]

3. Using removeIf() method

Both above solutions does not modify the original list, but creates a copy of the original list. If you want to modify the list inplace, you can use the removeIf() method. The removeIf() method removes all elements that satisfy the specified predicate. This is demonstrated below:

Download  Run Code

Output:

[A, B, , C, D, , E, ]
[A, B, C, D, E, ]
[A, B, C, D, E]

That’s all about filtering null, empty, and blank values from a list in Java.