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

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