如何从Kotlin中的列表中删除distinctBy的重复对象?
如何在自定义对象列表上使用distinctBy
来去除重复项? 我想通过对象的多个属性来确定“唯一性”,但不是全部。
我希望像这样的事情会起作用,但没有运气:
val uniqueObjects = myObjectList.distinctBy { it.myField, it.myOtherField }
编辑:我很好奇如何使用distinctBy
与任何数量的属性,不只是像我上面的例子中的两个。
你可以创建一对:
myObjectList.distinctBy { Pair(it.myField, it.myOtherField) }
distinctBy
将使用Pair
相等性来确定唯一性。
如果你看一下distinctBy
的实现,它只是将你在lambda中传递的值添加到Set
。 如果Set
没有包含指定的元素,则将原始List
的相应项添加到新List
并且作为distinctBy
的结果返回新List
。
public inline fun Iterable.distinctBy(selector: (T) -> K): List { val set = HashSet() val list = ArrayList() for (e in this) { val key = selector(e) if (set.add(key)) list.add(e) } return list }
所以你可以传递一个复合对象来保存你需要的属性来find唯一性。
data class Selector(val property1: String, val property2: String, ...)
并在lambda中传递该Selector
对象:
myObjectList.distinctBy { Selector(it.property1, it.property2, ...) }