android - 如何在 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 确定的元素)。
有没有一种简单的方法可以实现这一点,还是我真的需要自己实现这个查找机制?
解决方案
由于 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)
}
顺便说一句,按照惯例,属性名称应始终以小写字母开头,除非它们是常量(在这种情况下,它们都是大写字母)。
推荐阅读
- asp.net-core - JWT 发行者无效的 Asp.Net Core
- corda - 实现一个模拟银行的 CorDapp
- html - UL - LI 中的 Div 未相互对齐
- multithreading - 当 SEGV 发生在与主线程不同的线程中时缺少核心文件
- android - 将顶部的 alpha 设置为 0%,将底部的 alpha 设置为 70% - Android - Kotlin
- laravel - Laravel cron 没有在给定的时间拍摄
- android - Android Studio 的 Gradle 问题
- c# - 如何在 Visual Studio 2019 中调试 ASP.Net MVC
- apple-news - Apple News 组件中的 Facebook 视频
- objective-c - 无法构建 Objective-C 模块“Firebase”