![](/img/trans.png)
[英]Kotlin way to update elements in one list from elements in another list?
[英]How to filter elements in one list by a property value not present in elements in another list?
我有以下代碼片段
val cachedNews = listOf(News(9, "https://009"), News(8, "https://234"), News(7, "https://345"))
val freshNews = listOf(News(1, "https://123"), News(2, "https://234"), News(3, "https://345"))
val result = freshNews.filter {fresh -> filter(cachedNews, fresh)}
private fun filter(cached: List<News>, fresh: News): Boolean {
cached.forEach { cachedItem ->
if (cachedItem.url == fresh.url) return true
}
return false }
當代碼運行時,如果cachedItem.url == fresh.url
列表被過濾,結果是一個列表,其中兩個列表的urls
是相同的。 但是,當我像cachedItem.url != fresh.url
這樣反轉相等時,列表根本沒有過濾。 執行順序發生變化。
當使用==
跡象,第一項freshNews
與第一項相比cachedNews
后的secondItem freshNews
用的secondItem相比cachedNews
等。
當我使用!=
符號時, freshNews
的所有項目只與cachedNews
的 firstItem 進行cachedNews
?
我錯過了什么還是我的代碼錯了?
我不確定具體問題是什么,因為你的方法很混亂。 您的自定義filter
函數實際上更像是一個contains
函數。
可能有用的是:
fun main() {
val cachedNews = listOf(News(9, "https://009"), News(8, "https://234"), News(7, "https://345"))
val freshNews = listOf(News(1, "https://123"), News(2, "https://234"), News(3, "https://345"))
val cachedUrls = cachedNews.map { it.url }.toSet()
val result = freshNews.filterNot { cachedUrls.contains(it.url) }
println(result)
}
結果:
[News(id=1, url=https://123)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.