どうも、ちょげ(@chogetarou)です。
distinctBy()関数でMutableList(ミュータブルリスト)の重複を削除する方法を紹介します。
方法

distinctBy()関数でMutableList(ミュータブルリスト)の重複を削除するには、toMutableList()を使います。
まず、mutableLIstからdistinctBy{}を呼び出します。
distinctBy{}のクロージャーに、itを記述します。
そして、distinctBy{}からtoMutableList()を呼び出します。
val result : MutableList<T> = list.distinctBy { it }.toMutableList()
上記のtoMutbaleList()は、distinctBy()を呼び出したMutableListの重複を削除したMutableListを返します。
使用例
fun main() {
val numbers = mutableListOf(1, 2, 2, 1, 3, 4, 1, 5, 3)
val result : MutableList<Int> = numbers.distinctBy { it }.toMutableList()
println(numbers)
println(result)
}
出力:
[1, 2, 2, 1, 3, 4, 1, 5, 3]
[1, 2, 3, 4, 5]
コメント