我想从列表中删除一种类型的所有重复对象。
例如。
val models: MutableList<Model> = MutableList<DrawableModel>
models.add(Student)
models.add(Student)
models.add(Teacher)
models.add(Teacher)
models.add(Teacher)
预期输出:
Student
Student
Teacher
我只想要列表中一位老师的实例。
我试过
models.distinctBy{ it is Teacher}
但它对整个列表而不是特定对象应用 distinct 并返回。
Student
Teacher
最佳答案
你可以尝试这样的事情:
object Kotlin
{
@JvmStatic
fun main(args: Array<String>)
{
val teacher = Teacher(0, "T1");
val student = Student(1, "S1")
val models = mutableListOf(teacher, teacher, student, student, student)
// creating new list which is connection of two lists. First -> only Students. Second -> Distinct Teacher
val newModels = models.filterIsInstance<Teacher>().distinct() + models.filterIsInstance<Student>()
println(models) // [Teacher(ID=0, name=T1), Teacher(ID=0, name=T1), Student(ID=1, name=S1), Student(ID=1, name=S1)]
println(newModels) // [Teacher(ID=0, name=T1), Student(ID=1, name=S1), Student(ID=1, name=S1)]
}
// classes like in the question.
open class Model(val id: Int)
data class Teacher(val ID: Int, val name: String) : Model(ID)
data class Student(val ID: Int, val name: String) : Model(ID)
所以基本上它是主要部分:
val newModels = models.filterIsInstance<Teacher>().distinct() + models.filterIsInstance<Student>()
关于android - Kotlin 代码从可变列表中删除一种特定类型的重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63795761/