Scala 如何在匹配另一个列表项时删除项目
Scala how to remove item while matching other list itme
我有以下 2 个列表 class
case class User(var userId: Int =0,
var userName: String ="",
var email: String="",
var password: String ="") {
def this() = this(0, "", "", "")
}
用户 class 的全局列表。
用户 class.
的本地列表
我想 remove/filter globalList 中与 localList 中的用户 ID 相同的所有项目。
我尝试了几个 api 但没有成功,例如 filterNot、filter、drop、dropWhile。请告诉我如何做到这一点。
diff
运算符 "Computes the multiset difference between this list and another sequence"。
scala> val global = List(0,1,2,3,4,5)
global: List[Int] = List(0, 1, 2, 3, 4, 5)
scala> val local = List(1,2,3)
local: List[Int] = List(1, 2, 3)
scala> global.diff(local)
res9: List[Int] = List(0, 4, 5)
您可以尝试以下方法:
val userIdSet = localList.map(_.userId).toSet
val filteredList = globalList.filterNot(u => userIdSet.contains(u.userId))
我有以下 2 个列表 class
case class User(var userId: Int =0,
var userName: String ="",
var email: String="",
var password: String ="") {
def this() = this(0, "", "", "")
}
用户 class 的全局列表。
用户 class.
的本地列表我想 remove/filter globalList 中与 localList 中的用户 ID 相同的所有项目。
我尝试了几个 api 但没有成功,例如 filterNot、filter、drop、dropWhile。请告诉我如何做到这一点。
diff
运算符 "Computes the multiset difference between this list and another sequence"。
scala> val global = List(0,1,2,3,4,5)
global: List[Int] = List(0, 1, 2, 3, 4, 5)
scala> val local = List(1,2,3)
local: List[Int] = List(1, 2, 3)
scala> global.diff(local)
res9: List[Int] = List(0, 4, 5)
您可以尝试以下方法:
val userIdSet = localList.map(_.userId).toSet
val filteredList = globalList.filterNot(u => userIdSet.contains(u.userId))