This article explores different ways to remove empty values from a List of strings in Kotlin.

1. Using removeAll() function

The removeAll() function remove all values from the list that are contained in the specified collection. To remove all null or empty strings from a list of strings, you can do like below:

Download Code

2. Using removeIf() function

Alternatively, you can also use the removeIf() function to remove all items from a list that satisfies the given predicate. A typical invocation for this function would look like:

Download Code

3. Using filter() function

To create a “copy” of the list without changing the original list, you can use filter the list by applying a specified predicate to each element. The following solution returns a list containing all elements that are not null with the filterNotNull() function.

Download Code

 
To remove both null and empty values, you can use the isNullOrEmpty() function, which returns true if the string is either null or empty. The following code example shows invocation for this method using the filter() function. Note that an element is removed only when the predicate returns false. To remove an element only when the predicate returns true, use the filterNot() function.

Download Code

4. Using Iterator

Finally, you can traverse through the list using a loop and remove all elements that are either null or equal to an empty string. However, it might throw a java.util.ConcurrentModificationException if the List’s remove() function is used. This is because the concurrent modification of the list is not allowed while iterating over it, except by the iterator’s own remove() function method.

This can be implemented as follows in Kotlin using Iterator’s remove() function.

Download Code

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