Remove null values from a map in Kotlin
This article explores different ways to remove null values from a map in Kotlin.
1. Using remove() function
To remove all occurrences of null values from the map, you can continuously call remove(null) on the collection returned by values property until all nulls are removed.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val map: MutableMap<String, String?> = HashMap() map["RED"] = "#FF0000" map["GREY"] = null map["BLUE"] = "#0000FF" map["YELLOW"] = null while (map.values.remove(null)) {} println(map) // {RED=#FF0000, BLUE=#0000FF} } |
2. Using removeAll() function
The removeAll() function removes all elements contained in the specified collection. To remove all occurrences of null values from the map, you can pass a singleton sequence containing only null.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val map: MutableMap<String, String?> = HashMap() map["RED"] = "#FF0000" map["GREY"] = null map["BLUE"] = "#0000FF" map["YELLOW"] = null map.values.removeAll(sequenceOf(null)) println(map) // {RED=#FF0000, BLUE=#0000FF} } |
3. Using removeIf() function
To filter null values from the map, you can use the removeIf() function. It removes all key/value pairs from the map that satisfy the given predicate.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val map: MutableMap<String, String?> = HashMap() map["RED"] = "#FF0000" map["GREY"] = null map["BLUE"] = "#0000FF" map["YELLOW"] = null map.values.removeIf { it == null } println(map) // {RED=#FF0000, BLUE=#0000FF} } |
4. Using Iterator
Another plausible way of iteration is using an iterator. The following code example demonstrates its usage to remove all key/value pairs with null values.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
fun <K, V> removeNulls(map: MutableMap<K, V?>) { val itr = map.entries.iterator() while (itr.hasNext()) { val curr = itr.next() if (curr.value == null) itr.remove() } } fun main() { val map: MutableMap<String, String?> = HashMap() map["RED"] = "#FF0000" map["GREY"] = null map["BLUE"] = "#0000FF" map["YELLOW"] = null removeNulls<String, String?>(map) println(map) // {RED=#FF0000, BLUE=#0000FF} } |
That’s all about removing null values from a map 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 :)