摘自Kotlin源码
package kotlin.collections
/**
* Returns a list containing only elements from the given collection
* having distinct keys returned by the given [selector] function.
*
* The elements in the resulting list are in the same order as they were in the source collection.
*/
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 AlarmBean( var alarmCreatedTimestamp: Long = 0 )
//创建集合
val list = mutableListOf<AlarmBean>()
//过滤去重字段
list.distinctBy { it.alarmCreatedTimestamp }