Replace values in a List in Kotlin
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:
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf("A", null, null, "B", "C", null, "D", null) list.replaceAll { it ?: "" } println(list) } |
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:
|
1 2 3 4 5 6 7 8 |
import java.util.* fun main() { val list = listOf("A", null, null, "B", "C", null, "D", null) Collections.replaceAll(list, null, "") println(list) } |
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.
|
1 2 3 4 5 |
fun main() { val list = listOf("A", null, null, "B", "C", null, "D", null) val newList = list.map { it ?: "" } println(newList) } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
data class Person(var name: String, var age: Int, var cat: String?) fun main() { val persons = listOf(Person("James", 18, null), Person("Mary", 20, null), Person("Jennifer", 25, null)) persons.filter { it.age < 18 }.forEach { it.cat = "Teen"} persons.filter { it.age >= 18 }.forEach { it.cat = "Adult"} println(persons) } |
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.
|
1 2 3 4 5 6 7 8 9 |
data class Person(var name: String, var age: Int, var cat: String?) fun main() { val persons = listOf(Person("James", 18, null), Person("Mary", 20, null), Person("Jennifer", 25, null)) persons.find { it.name == "Mary" }?.age = 21 println(persons) } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)