どうも、ちょげ(@chogetarou)です。
removeIf()を使ってMutableList(ミュータブルリスト)のNullを削除する方法を紹介します。
方法

removeIf()を使ってMutableList(ミュータブルリスト)のNullを削除するには、ラムダ式を使います。
まず、MutableListからremoveIf{}を呼び出します。
そして、removeIf{}のクロージャーに、「ラムダ式の引数 == null」という条件式を返すラムダ式を指定します。
//T=要素の型
list.removeIf { item : T? -> item == null }
上記のremoveIf()は、呼び出したMutableListからnullを削除します。
使用例
fun main() {
val numbers : MutableList<Int?> = mutableListOf(null, 1, 2, null, 3, null, null, 4, 5)
numbers.removeIf { number : Int? -> number == null }
println(numbers)
}
出力:
[1, 2, 3, 4, 5]
コメント