如何从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 <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, ...) }