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