如何通过另一个列表中元素中不存在的 属性 值过滤一个列表中的元素?

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 }

当代码运行时 if cachedItem.url == fresh.url 列表被过滤,结果是两个列表的 urls 相同的列表。但是,当我像这样 cachedItem.url != fresh.url 反转相等时,列表根本没有被过滤。执行顺序发生变化。

当使用==符号时,freshNews的第一项与cachedNews的第一项进行比较,然后freshNews的第二项与第二项进行比较cachedNews 等等。

当我使用 != 符号时,freshNews 的所有项目仅与 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)]