This article explores different ways to replace values in a list in Kotlin.

1. Using replaceAll() function

The standard solution to replace values in a list is using the replaceAll() function. It replaces each element of the list with the result of applying the specified operator to it. For instance, the following code replaces null values in a List<String> with an empty string:

Download Code

Output:

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

2. Using Collections.replaceAll() function

Another option is to use the Collections.replaceAll() function to replace all occurrences of the specified value in a list with another. A typical implementation of this approach would look like below:

Download Code

Output:

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

3. Using map() function

The replaceAll() function in-place modifies the original list. To avoid modifications to the original list, we can use the map() function, which applies a given function to each element of the input list.

Download Code

Output:

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

4. Using filter() function

To “conditionally” modify a field in a list of objects, we can filter the list using the filter() function and perform the given action on each element of the filtered list:

Download Code

Output:

[Person(name=James, age=18, cat=Adult), Person(name=Mary, age=20, cat=Adult), Person(name=Jennifer, age=25, cat=Adult)]

 
To only modify the first matching object, use the find() function.

Download Code

Output:

[Person(name=James, age=18, cat=null), Person(name=Mary, age=21, cat=null), Person(name=Jennifer, age=25, cat=null)]

That’s all about replacing values in a list in Kotlin.