1. 引言
在 Kotlin 中使用列表时,经常需要移除空值和 null 值。null 值可能会在我们的代码中引起错误,而空值可能会给我们的列表增加不必要的冗余。
在本教程中,我们将探索在 Kotlin 中从列表中移除 null 和空值的不同方法。
2. 使用简单的列表迭代
我们将使用的第一个方法是程序化方法。它涉及遍历列表,并在此过程中移除所有 null 和空元素:
fun removeValuesViaIteration(listWithNullsAndEmpty: MutableList````````````<String?>````````````): List``````````````<String>`````````````` {
val iterator = listWithNullsAndEmpty.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
if (element == null || element.isEmpty()) {
iterator.remove()
}
}
return listWithNullsAndEmpty as List``````````````<String>``````````````
}
大约 8 分钟