簡體   English   中英

如何通過另一個列表中的元素中不存在的屬性值過濾一個列表中的元素?

[英]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函數。

可能有用的是:

  1. 將緩存的 URL 提取到一組
  2. 按不在集合中的 URL 過濾新結果。
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM