如何从Kotlin中的列表中删除带有distinctBy的重复对象?

时间:2017-08-25 14:31:34

标签: kotlin

如何在自定义对象列表中使用distinctBy来删除重复项?我想通过对象的多个属性确定“唯一性”,但不是全部。

我希望这样的东西可行,但没有运气:

val uniqueObjects = myObjectList.distinctBy { it.myField, it.myOtherField }

编辑:我很好奇如何将distinctBy与任意数量的属性一起使用,而不仅仅像上面的例子中那样使用两个属性。

2 个答案:

答案 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, ...) }