首页 > 解决方案 > 如何在 SortedList 中按特定条件查找/删除项目?

问题描述

我的代码中有此代码class OutlookItemsAdapter: RecyclerView.Adapter<OutlookItemsViewHolder>()

companion object {
    lateinit var outlookItems: SortedList<OutlookItem>
}

init {
    outlookItems = SortedList(OutlookItem::class.java, object: SortedListAdapterCallback<OutlookItem>(this){
        override fun areItemsTheSame(item1: OutlookItem, item2: OutlookItem): Boolean = item1 == item2

        override fun compare(o1: OutlookItem, o2: OutlookItem): Int = o1.DateTime.compareTo(o2.DateTime)

        override fun areContentsTheSame(oldItem: OutlookItem, newItem: OutlookItem): Boolean = oldItem.EntryId.equals(newItem.EntryId)
    })
}

在哪里OutlookItem

class OutlookItem (
    val Subject: String,
    val EntryId: String,
    val DateTime: LocalDateTime,
    val MeetingUrl: String?
)

我需要编写一个函数来接收并从列表中EntryId删除它的等价物。OutlookItem不幸SortedList的是没有这种能力(即查找/删除由某些 lambda 确定的元素)。

有没有一种简单的方法可以实现这一点,还是我真的需要自己实现这个查找机制?

标签: androidkotlin

解决方案


由于 SortedList 实际上并没有实现 List 接口,因此您不能将 Kotlin 的任何辅助高阶函数用于其上的 Lists。

查找高阶函数可以这样写:

inline fun <T> SortedList<T>.firstOrNull(predicate: (T) -> Boolean): T? {
    for (index in 0 until size()){
        this[index].let { 
            if (predicate(it)) return it
        }
    }
    return null
}

然后您可以使用它来执行您描述的任务,如下所示:

fun SortedList<OutlookItem>.removeByEntryId(entryId: String) {
    val item = firstOrNull { it.EntryId == entryId }
    if (item != null) remove(item)
}

顺便说一句,按照惯例,属性名称应始终以小写字母开头,除非它们是常量(在这种情况下,它们都是大写字母)。


推荐阅读