How to remove duplicate objects using clearBy from a list in Kotlin?

How can I use distinctBya list of custom objects to cut duplicates? I want to define "uniqueness" by several properties of an object, but not all of them.

I was hoping this would work, but no luck:

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

Edit: I am wondering how to use distinctBywith any number of properties, not just two, as in my example above.

+4
source share
2 answers

You can create a pair:

myObjectList.distinctBy { Pair(it.myField, it.myOtherField) }

distinctBywill use equality Pairto determine uniqueness.

+9
source

distinctBy, , , 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, ...)

Selector :

myObjectList.distinctBy { Selector(it.property1, it.property2, ...) }
+3

Source: https://habr.com/ru/post/1684474/


All Articles