Introduction
This quick will show how to remove all null values from a list in Java using plain Java in three different ways.
RemoveIf() to remove all null values from a list
With Java 8 and higher, we can use the removeIf method to remove nulls from the fruits list.
RemoveIf alters the original list, meaning it will remove the null values from the list of the fruit.
| |
Remove() to remove all nulls from a list
We use a while loop in the following example to remove null values from the fruits list.
The while loop will run until it has removed all the null values individually.
| |
filter() to remove all nulls from a list
With Java 8, we can also use streams to create a list without the null values. Using stream will not alter the original list but create a copy of the list without the null values.
| |
Conclusion
In this article, we showed how to remove null values using streams, List.removeIf(), and a for-loop.